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.