简体   繁体   English

我的删除按钮 gridview 中的行索引错误

[英]Row Index error in my delete button gridview

This code that im showing is totally working fine in cell click event.我显示的这段代码在单元格单击事件中完全正常。 But i've inserted some buttons in the gridview and one of that is the "delete" button.但是我在 gridview 中插入了一些按钮,其中之一是“删除”按钮。 While I was transferring the code from the cell click event to the button delete, I encounter this error.当我将代码从单元格单击事件传输到按钮删除时,我遇到了这个错误。 Can somebody please tell me what do I need to change in the code so that the delete function will be fix?有人可以告诉我我需要在代码中更改什么才能修复删除功能吗?

private void button3_Click(object sender, EventArgs e)
        {
            string maincon = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            SqlConnection sqlcon = new SqlConnection(maincon);
            string rfidno = dataGridView1.Rows[e.RowIndex].Cells["rfidno"].FormattedValue.ToString();

            DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete this information?", "Delete function triggered", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                try
                {
                    SqlDataAdapter da = new SqlDataAdapter();
                    sqlcon.Open();
                    da.DeleteCommand = new SqlCommand("delete from tbl_registerStudent where rfidno = '" + rfidno + "'", sqlcon);
                    da.DeleteCommand.ExecuteNonQuery();

                    MessageBox.Show("" + rfidno);
                    MessageBox.Show("Delete Successfull");
                    sqlcon.Close();
                    bindGrid();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else if (dialogResult == DialogResult.No)
            {
                CreateID objs = new CreateID();
                if (objs == null)
                {
                    objs.Parent = this;
                }
                objs.Show();
                this.Hide();
            }
        }

在此处输入图片说明

You can't use e.RowIndex in a buttonclick event handler because the e that is passed in doesn't have that property.您不能在 buttonclick 事件处理程序中使用 e.RowIndex,因为传入的e没有该属性。

You should handle this in the same way you previously did;你应该像以前一样处理这个问题; attach a handler to the CellContentClick of the datagridview and carry out this code if the column that is clicked is the button column Ie don't do this:将处理程序附加到 datagridview 的 CellContentClick 并执行此代码,如果单击的列是按钮列,即不要这样做:

While I was transferring the code from the cell click event当我从单元格单击事件传输代码时

Just make the cell click event test "if the column that was clicked is the button column then..."只需进行单元格单击事件测试“如果单击的列是按钮列,则......”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM