0

I am trying to query my DataSet and display the results in an unbound 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.

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). I think I am getting the exception right away (i is still 0 in debugger). I first tried it using just row[i] but got the same error.

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.

4

1 回答 1

1

在访问之前DataGridView1.Rows[i].Cells[j],您需要确保 DataGridView1.Rows[i]存在。如果没有,您需要将其添加到DataGridViewRowCollection.

您可以在此页面上找到很多示例。

于 2013-06-05T18:10:35.310 回答