[英]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.