2014-01-07 42 views
0

IndexOutOfRange的錯誤 - 無法找到表0 - 這是我的代碼,它擊中了每條線,並引發錯誤。我應該更新什麼,以便執行?數據集調試錯誤

SqlCommand comnd = new SqlCommand(query, con); 
con.Open(); 
DataSet ds = new DataSet(); 
StreamWriter strmwr = new StreamWriter(Location); 
foreach (DataRow in ds.Tables[0].Rows 
+0

您正在實例化一個新的數據集,然後嘗試訪問表[0]?你的數據集在那時是空的。你肯定會得到一個錯誤 –

回答

2

你創建一個空的DataSet沒有表。您是否想要Fill數據集?

SqlCommand comnd = new SqlCommand(query, con); 
con.Open(); 
SqlDataAdapter da = new SQlDataAdapter(comnd); // create a DataAdapter 
DataSet ds = new DataSet(); 
StreamWriter strmwr = new StreamWriter(Location); // Not sure what this is for 
da.Fill(ds); // fill the DAtaSet 

foreach (DataRow in ds.Tables[0].Rows 

我不包括任何using聲明,但建議你換到的所有命令和連接。

2

你永遠填充DataSet - 你創建一個SQL命令,但從來沒有執行它。你根本不查詢數據庫。

目前尚不清楚您是否真的需要DataSet, to be honest - you could potentially just use a reader returned by [ ExecuteReader ][1]. Personally I'd go in that direction, as I'm not a big fan of DataSet。 (另外,我會使用ORM來避免這一切的工作級別低...)

(請注意,您應該使用using報表的作家,命令等)

如果你真的需要一個DataSet,你可能想看看SqlDataAdapter

var adapter = new SqlDataAdapter(command); 
adapter.Fill(ds); 
// Now your DataSet will have data in it 
+0

我真的想修復那個缺少的反引號,但它只是一個字符。 – Johnbot