在我的datagridview

时间:2017-05-17 22:10:05

标签: c# datagridview

我正在尝试在我的datagridview上的已检查行上实现删除按钮,如下所示,但我收到错误(消息=索引超出范围。必须是非负数且小于集合的大小。)< / p>

注意:即使我检查了多条记录,它也会删除一条记录。

    private void btnDelete_Click(object sender, EventArgs e) 
    {
        if (MessageBox.Show("You Choose to delete selected records\n Are you sure?", "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            for (int i = dGVCustomer.Rows.Count - 1; i >= 0; i--)
            {
                object Cell = dGVCustomer.Rows[i].Cells["Edit"].Value;
                int customer_id = (int)dGVCustomer.Rows[i].Cells["Customer_ID"].Value;
                if (Cell.ToString() == "True")
                {
                    DeleteRecord(customer_id);
                }
            }
        }
    }




    private int DeleteRecord(int p_customer_id)
    {
        string cmdstr = @"delete from customers where customer_id = @p_customer_id";

        try
        {
            using (MySqlConnection conn = new MySqlConnection(ConnStr))
            using (MySqlCommand cmd = new MySqlCommand(cmdstr, conn))
            {
                conn.Open();

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = cmdstr;

                cmd.Parameters.Clear();

                cmd.Parameters.AddWithValue("@p_customer_id", MySqlDbType.Int32).Value = p_customer_id;

                cmd.ExecuteNonQuery();

                this.Close();
            }
            return 1;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

0 个答案:

没有答案