Harvey
Harvey

Reputation: 389

index was out of range. must be nonnegative and less than the size of the collection. in c#

In my application it has two datagridviews named datagridview1 and datagridview2 and I have the selectionChanged event in datagridview1 that captures the data that is selected in it so that the content of datagridview2 is also changed based on what the product name of the selected row in datagridview1 is. I don't know why I have an index that is out of range because I have checked that I have at least 1 row and 2 columns in datagridview1. I am using DataView RowFilter function.

Here is my code:

private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
    view_1.RowFilter = "product_name = '" + datagridview1.SelectedRows[0].Cells[1].Value.ToString() +"'";
}

Upvotes: 1

Views: 2884

Answers (2)

Harvey
Harvey

Reputation: 389

Like Yorye Nathan said "You should first check if it's Length is greater than zero, and only if it is, continue with the function."

private void datagridview1_SelectionChanged(object sender, EventArgs e)
        {
            if(dataGridView1.SelectedRows.Count > 0)
            {
               view_1.RowFilter = "product_name = '" + datagridview1.SelectedRows[0].Cells[1].Value.ToString() +"'";
            }

        }

Upvotes: 0

YoryeNathan
YoryeNathan

Reputation: 14522

The SelectionChanged event should fire when you unselect rows as well, so the SelectedRows should be empty and therefore you cannot index into it at all.

You should first check if it's Length is greater than zero, and only if it is, continue with the function.

Also, since I see you only handle a single selected row, I suggest you make sure you don't allow multi-row-selection on the DataGridView control (unless needed for something else, such as delete or whatever).

Upvotes: 3

Related Questions