[英]Adding DataRow[] data to each column in an unbound DataGridView?
我試圖查詢我的DataSet並在未綁定的DataGridView中顯示結果。 我覺得我的編程邏輯與我很接近,但是我一直收到錯誤ArgumentOutOfRange Exception. Index was out of range. Must be non-negative and less than the size of the collection.
ArgumentOutOfRange Exception. Index was out of range. Must be non-negative and less than the size of the collection.
我的代碼段:
DataRow[] foundRows;
//Queries the Reservations table with the 'searchExpression' variable
foundRows = this.reservationMasterDataSet.Tables["Reservations"].Select(searchExpression);
//If there is at least one record found...
if (foundRows.Length > 0)
{
//Used to count our row indexes
int i = 0;
//Populate the DataGridView with the queried response
foreach (DataRow row in foundRows)
{
//Used to count our column indexes
for (int j = 0; j < reservationMasterDataSet.Tables["Reservations"].Columns.Count; j++)
{
//THIS LINE IS THROWING AN EXCEPTION
dataGridView1.Rows[i].Cells[j].Value = row.ItemArray[j];
}
i++;
}
}
我的DataRow
包含12個對象,因此我確保DataGridView
具有12個對應的列(原始數據庫中有12個列)。 我想我馬上就收到異常(調試器中i
仍然為0
)。 我首先僅使用row[i]
了嘗試,但遇到了相同的錯誤。
這意味着是搜索結果窗格,而不是可編輯的內容,這就是為什么我只想返回某些結果的原因。 我認為DataGridView
是在Windows窗體上布局記錄的最佳方法。
在訪問DataGridView1.Rows[i].Cells[j]
,需要確保DataGridView1.Rows[i]
存在。 如果否,則需要將其添加到DataGridViewRowCollection
。
您可以在此頁面上找到很多示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.