通过文本框从datagridview进行行更新时引发异常 [英] Throws exception when for row update from datagridview by textboxes

查看:67
本文介绍了通过文本框从datagridview进行行更新时引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击更新按钮后,我想更新datagridview和sql数据库中的选定行。这是我的代码但是它引发了一个例外,索引超出了范围。必须是非负的并且小于集合的大小。

请指教我,谢谢:)



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 :)

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]已添加代码块[ / edit]



[edit]Code block added[/edit]

推荐答案

原因是: dataGridView1.SelectedRows 为零行数。有时,没有选择任何行,对吧?

您应该始终提供全面的异常信息。你甚至没有指出抛出异常的代码行。



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


这篇关于通过文本框从datagridview进行行更新时引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆