Csharp_learner
Csharp_learner

Reputation: 341

System Argument out of range exception in C# while adding rows to datagridview

I have a code as follows:

private void svars_MouseDoubleClick(object sender, MouseEventArgs e)
        {



            userSelection user_sel = new userSelection();
            string file = svars.SelectedItem.ToString();

            DataGridViewRow row = new DataGridViewRow();



            dataGridView1.Rows.Add(row);

            row.Cells["Local_Variables"].Value = "test";

            DataGridViewCell sysvar = new DataGridViewTextBoxCell();
            sysvar.Value = file;
            row.Cells["System_Variables"] = sysvar;

        }

I am getting error following error:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll

Additional information: Specified argument was out of the range of valid values.

When I tried to debug I found that row.Index is -1. I am not sure how to fix it. Can anyone please help.

Thanks.

Upvotes: 1

Views: 2626

Answers (1)

Lander
Lander

Reputation: 3437

The Cells "Local_Variables" and "System_Variables" do not exist in row.Cells. Make sure you first add them.

dataGridView1.Columns.Add("Local_Variables", "Local Variables");
dataGridView1.Columns.Add("System_Variables", "Local Variables");

If the columns are already there, then check their Key values to ensure that they're set properly.

Upvotes: 2

Related Questions