Rashedur Rahman
Rashedur Rahman

Reputation: 359

Argument index out of range in datagrid view c# windows form

Can anyone help me telling why argument index out range error occur in c# while selecting multiple rows in datagridview in c#...My code is also given bellow...the error is after the else if (comboBox2.Text == "Choice 2") portion......

 if (comboBox2.Text == "")
        {
            comboBox2.Focus();
            // comboBox2.BackColor = Color.Red;
        }
        else
        {
            if (comboBox2.Text == "Choice 1")
            {

                int ri = dataGridView1.CurrentCell.RowIndex;
                int ci = dataGridView1.CurrentCell.ColumnIndex;
                label4.Show();
                textBox2.Show();
                textBox2.Text = dataGridView1.SelectedRows[ri].Cells["course_name"].Value.ToString();

            }
            else if (comboBox2.Text == "Choice 2")
            {

                int ri = dataGridView2.CurrentCell.RowIndex;
                int ci = dataGridView2.CurrentCell.ColumnIndex;
                label3.Show();
                textBox4.Text = dataGridView2.SelectedRows[ri].Cells["course_name"].Value.ToString();
                textBox4.Show();
            }
            else if (comboBox2.Text == "Choice 3")
            {

                int ri = dataGridView3.CurrentCell.RowIndex;
                int ci = dataGridView3.CurrentCell.ColumnIndex;
                label2.Show();
                textBox3.Text = dataGridView3.SelectedRows[ri].Cells["course_name"].Value.ToString();
                textBox3.Show();
            }
        }

Upvotes: 1

Views: 947

Answers (1)

Steve
Steve

Reputation: 216273

DataGridView.SelectedRows is a collection that contains the Rows selected. It has the same number of rows of the grid only if you select every row in the grid. But I think you are only selecting a few rows. So, the RowIndex of the current cell is not a valid index inside the SelectedRows collection.

You need to change your code to something more secure

 if(dataGridView3.SelectedRows.Count > 0)
 {
      textBox3.Text = dataGridView3.SelectedRows[0].Cells["course_name"].Value.ToString();
      ....

or using the currentRow property.

 DataGridViewRow currentRow = dataGridView3.CurrentRow;
 if(dataGridView3.SelectedRows.Contains(currentRow))
 {
      textBox3.Text = currentRow.Cells["course_name"].Value.ToString();
      ....

but if you just want to set the TextBox3.Text to the cell "course_name" of the currentRow, then there is no need to involve the SelectedRows collection

 if(dataGridView3.CurrentRow != null)
      textBox3.Text = dataGridView3.CurrentRow.Cells["course_name"].Value.ToString();

Upvotes: 1

Related Questions