Click here to Skip to main content
15,942,449 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void btnpass_Click(object sender, EventArgs e)
      {
          Inventory coo = new Inventory(dataGridView1.SelectedRows[0].Cells[0].Value.ToString(),
          dataGridView1.SelectedRows[0].Cells[1].Value.ToString(),
          dataGridView1.SelectedRows[0].Cells[2].Value.ToString(),
          dataGridView1.SelectedRows[0].Cells[3].Value.ToString(),
          dataGridView1.SelectedRows[0].Cells[4].Value.ToString(),
          dataGridView1.SelectedRows[0].Cells[5].Value.ToString(),
           dataGridView1.SelectedRows[0].Cells[6].Value.ToString());
          coo.Show();
      }

What I have tried:

Itried Pass selected row gridview to another gridview on another form but show error.
error is (Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index)
i use different method but not my problem solve
Posted
Updated 13-May-16 20:31pm

1 solution

Index out of range error means you are trying to read the value from an index which is not present. to avoid this exception you have validate before accessing the index..

C#
private void button1_Click(object sender, EventArgs e)
       {
           var selectedRows = dataGridView1.SelectedRows;
           if (selectedRows != null && selectedRows.Count > 0) // validate the index
           {
               DataGridViewCellCollection cells = selectedRows[0].Cells;
               if (cells.Count >= 7) // validate the index
               {
                   Inventory coo = new Inventory(
                      cells[0].Value.ToString(),
                      cells[1].Value.ToString(),
                      cells[2].Value.ToString(),
                      cells[3].Value.ToString(),
                      cells[4].Value.ToString(),
                      cells[5].Value.ToString(),
                      cells[6].Value.ToString());
                      coo.Show();
               }
           }
       }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900