2014-01-07 50 views
7

我在我的C#代碼中迭代DataTable。我嘗試使用使用名爲「行」行命名爲「列名」一欄來獲得內容 -列abc不屬於表?

object value = row["ColumnName"]; 

我得到這個錯誤 -

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Column 'FULL_COUNT' does not belong to table . at System.Data.DataRow.GetDataColumn(String columnName)

這怎麼可能?我的SQL查詢/結果集有一個名稱的列,查詢甚至運行在管理工作室。

如何解決此錯誤?

+0

你能發表更多的代碼嗎? – Szymon

+0

請說明如何查詢數據庫以開始。您可能還想查看錶格中的所有列以確定*已被選中。 –

+0

@JonSkeet - 好的。我將需要一些時間在示例表中複製問題。很快就會做到。 – Steam

回答

11

我猜你的代碼是迭代應該是這樣的

DataTable table = new DataTable(); 
foreach (DataRow row in table.Rows) { 
    foreach (DataColumn col in table.Columns) { 
     object value = row[col.ColumnName]; 
    } 
} 

如果是這樣的話,row["ColumnName"]在每次迭代中查找與名稱ColumnName同一列,這顯然不會在你的表中存在。

正確的方法是在迭代row[ColumnName]row[col.ColumnName]以上

+1

我認爲它應該是'foreach(table.Rows中的DataRow行)'。 – Alice

+0

最好是我固定它 – AaA

-2

我有同樣的問題,試圖通過對同一產品的兩個不同的密鑰。

item.Product = SqlHelper.GetSafeString(dr, "ProductName"); 
    item.Product = SqlHelper.GetSafeString(dr, "Product"); 
0

不要編寫Gradeview列名稱而不寫數據庫列名稱。

dataGridViewEmployeeClass.Rows[n].Cells[0].Value = item["write there Database ColumnS names"].ToString(); 
0

我對我的c#代碼有一個類似的問題,使用我已成功初始化並使用數據庫中的數據填充的數據集。

所以我回集顯:

data = new Byte[0];

data = (Byte[])(dataset.Tables[0].Rows[0]["systemLogo_img"]);

當然的錯誤是在T找到列 'systemLogo_img'。

我注意到,你根本不必調用/限定列名。所以更正是:

data = new Byte[0];

data = (Byte[])(dataset.Tables[0].Rows[0].ItemArray[0]);

簡而言之:在位置使用「ItemArray」。

謝謝