Search code examples
c#.netdatagridviewdatagridviewcolumndatagridviewcheckboxcell

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


I want to delete checked rows in DatagGidView from the database , I searched the available questions in this site but i cannot find the exact answer how to avoid null value error if checkbox not checked for the row.

I created DataGridViewCheckBoxColumn, and I need to delete selected (checked) rows from database when click delete button.

DGV

I tried the following code:

First I created the DataGridViewCheckBoxColumn when get data from the database

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

Then the code for delete button I tried more than one solution checking null value but also not working :

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);
}

I tried the following questions also but no exact solution for my case:

I need the exact answer please I am new to .NET what to do to fix this error?


Solution

  • Thank you Mr JQSOFT for your answer , I changed the following :

    dgvprice.Columns.Insert(0, checkboxdelete); 
    

    instead of

    dgvprice.Columns.Add(checkboxdelete);
    

    then the delete button changed

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

    instead of

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