简体   繁体   中英

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

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:

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..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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