Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
After update button is clicked, I would want to update the selected row in datagridview and sql database. This is my code but however it throws me an exception, "Index was out of range. Must be non-negative and less than the size of the collection."
Please advise me, thank you :)

C#
private void UpdateButton_Click(object sender, EventArgs e)
{
  if (tbx_Name.Text.Equals("") || tbx_Desc.Text.Equals(""))
  {
      MessageBox.Show("Fill in all forms");

  }
  else
  {
      int selectedRow;
      selectedRow = dataGridView1.SelectedRows[0].Index;
      Bag newBag= new Bag();
      newBag.Name = tbx_Name.Text;
      newBag.Desc = tbx_Desc.Text;
      dataGridView1.Rows[selectedRow].SetValues(tbx_Name.Text, tbx_Desc.Text);

      if (DBManager.UpdateBag(newBag) == 1)
      {
          MessageBox.Show("Update is successful");
      }
       else
         {
           MessageBox.Show("Update is not successful");
           }
  }


[edit]Code block added[/edit]
Posted
Updated 17-Jun-13 4:57am
v2
Comments
Mahesh Bailwal 17-Jun-13 10:19am    
Please debug and check the value of selectedRow, it might be -1.
dolphinlover2013 17-Jun-13 10:52am    
The value is 0. Which is weird because after selecting the cell in datagridview, data are transferred into textboxes. I change the values in the textbox and click on the update button, the exception error is thrown.

1 solution

The reason is: dataGridView1.SelectedRows has zero count of rows. Sometimes, no rows are selected, right?
You should always provide comprehensive exception information. You did not even indicate the line of code where the exception was thrown.

—SA
 
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