R.JN R.JN - 1 year ago 76
SQL Question

excpetion error :Index was out of range. Must be non-negative and less than the size of the collection

I have seen all the exception errors but I didn't get my problem. I have tblsecondary which have streetId,streetName,fasileOne,fasileTwo. I am using a datagridview to populate a row when I select a value in datagridviewcomboboxcolumn, but its giving me an exception error :

Index was out of range. Must be non-negative and less than the size of the collection.

on dataGridView7[e.RowIndex, 2].Value = drFound["fasileOne"];

The code is :

private void dataGridView7_CellValueChanged(object sender, DataGridViewCellEventArgs e)
if ((e.RowIndex >= 0) && (e.ColumnIndex == 1)) // Assuming this is the streetId
int streetId = Convert.ToInt16(dataGridView7.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
DataRow drFound = tblSecondary.Rows.Find(streetId);
if (drFound == null)
dataGridView7[e.RowIndex, 2].Value = drFound["fasileOne"];
dataGridView7[e.RowIndex, 3].Value = drFound["fasileTwo"];

Here is the datatable am using :

public IncidentForm()
tblSecondary = new DataTable();
SqlCommand cmd2 = cnn.CreateCommand();
cmd2.CommandText = "select * from street";
SqlDataAdapter sdr2 = new SqlDataAdapter(cmd2);
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cnn;
tblSecondary.PrimaryKey = new DataColumn[] { tblSecondary.Columns["streetId"] };

Answer Source

The problem is the indexer on the DataGridView.
The first index is the ColumnIndex, the second the RowIndex

 dataGridView7[2, e.RowIndex].Value = drFound["fasileOne"];
 dataGridView7[3, e.RowIndex].Value = drFound["fasileTwo"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download