简体   繁体   English

将DataRow []数据添加到未绑定的DataGridView中的每一列?

[英]Adding DataRow[] data to each column in an unbound DataGridView?

I am trying to query my DataSet and display the results in an unbound DataGridView. 我试图查询我的DataSet并在未绑定的DataGridView中显示结果。 I feel like I am quite close with my programming logic here, but I keep getting the error 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. ArgumentOutOfRange Exception. Index was out of range. Must be non-negative and less than the size of the collection.

My code snippet: 我的代码段:

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++;
        }
}

My DataRow contains 12 objects so I made sure that the DataGridView has 12 columns to correspond (and there are 12 in the original database). 我的DataRow包含12个对象,因此我确保DataGridView具有12个对应的列(原始数据库中有12个列)。 I think I am getting the exception right away ( i is still 0 in debugger). 我想我马上就收到异常(调试器中i仍然为0 )。 I first tried it using just row[i] but got the same error. 我首先仅使用row[i]了尝试,但遇到了相同的错误。

This is meant to be a search results pane, not an editable thing, which is why I want to only return certain results. 这意味着是搜索结果窗格,而不是可编辑的内容,这就是为什么我只想返回某些结果的原因。 I figured the DataGridView is the nicest and easiest way to layout the record on a Windows form. 我认为DataGridView是在Windows窗体上布局记录的最佳方法。

Before you access to DataGridView1.Rows[i].Cells[j] , you need to make sure DataGridView1.Rows[i] exists. 在访问DataGridView1.Rows[i].Cells[j] ,需要确保DataGridView1.Rows[i]存在。 If no, you need to add it to the DataGridViewRowCollection . 如果否,则需要将其添加到DataGridViewRowCollection

You can find a lot of sample on on this page . 您可以在此页面上找到很多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM