如何为 DataGridViewCheckBoxColumn 提供初始值并修复错误 Object reference not set to an instance of an object?

How to give initial value for DataGridViewCheckBoxColumn and fix error Object reference not set to an instance of an object?

我想从数据库中删除 DatagGidView 中选中的行,我搜索了该站点中的可用问题,但我找不到确切的答案如果未选中该行的复选框,如何避免空值错误。

我创建了 DataGridViewCheckBoxColumn,我需要在单击删除按钮时从数据库中删除选定(选中)的行。

我尝试了以下代码:

首先我在从数据库获取数据时创建了 DataGridViewCheckBoxColumn

DataGridViewCheckBoxColumn checkboxdelete = new DataGridViewCheckBoxColumn();
dgvprice.Columns.Add(checkboxdelete);
checkboxdelete.HeaderText = "Select";
checkboxdelete.Name = "delete";
dgvprice.DataSource = pricelist.GET_CUSTOMER_PRICELIST(Convert.ToInt32(textCustId.Text));

然后删除按钮的代码我尝试了不止一种检查空值的解决方案,但也没有用:

private void btndelete_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dgvprice.Rows)
    {
        // if (!string.IsNullOrEmpty(row.Cells[0].ToString()) && !string.IsNullOrEmpty(row.Cells[0].Value.ToString()))

        bool status = (bool)dgvprice.Rows[0].Cells[0].Value;
        if (status)
        {
            string cs = ConfigurationManager.ConnectionStrings["mamlakalabConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand("delete from Customers_Price_List where testid = '" + row.Cells[1].Value.ToString() + "' and custid = '" + textCustId.Text + "'", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    MessageBox.Show("Deleted Successfully", "Successfull operation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

我也尝试了以下问题,但没有针对我的情况的确切解决方案:

我需要确切的答案,我是 .NET 的新手 如何修复此错误?

谢谢JQSOFT先生的回答, 我更改了以下内容:

dgvprice.Columns.Insert(0, checkboxdelete); 

而不是

dgvprice.Columns.Add(checkboxdelete);

然后删除按钮改变了

bool status = (bool)row.Cells[0].FormattedValue; 

而不是

bool status = (bool)dgvprice.Rows[0].Cells[0].Value;