Object reference not set to an instance of an object

andrewmanuja

Well-known member
Joined
May 30, 2019
Messages
75
Programming Experience
Beginner
Hi All,
I got a dataGridView and the first column's column type is " DataGridViewCheckBoxColumn".
My requirement is, I want to pass the data from the dataGridView based on the checked item rows to the database.

My code looks like below and when running the application, I am getting the "Object Reference not set to an Instance of an Object".
The error I am getting at the "if" condition.
C#:
if (ReturnQty > 0)
{
    foreach (DataGridViewRow row in dataGridViewDrugReturn.Rows)
    {
        if ((bool)row.Cells["textselectItem"].Value ==true)
        {
            cmd.Parameters.Clear();
            cmd = new SqlCommand(@"UPDATE tbl_CostCentreDrugStock SET availableQuantity += @areturnQuantity WHERE costCentreID = @acostCentreID AND drugID = @adrugID", con);
            cmd.Parameters.AddWithValue("@acostCentreID", txtCostCentreID.Text);

            cmd.Parameters.AddWithValue("@adrugID", Convert.ToInt32(row.Cells["textdrugID"].Value == DBNull.Value ? "0" : row.Cells["textdrugID"].Value.ToString()));
            cmd.Parameters.AddWithValue("@areturnQuantity", Convert.ToInt32(row.Cells["textreturnQuantity"].Value == DBNull.Value ? "0" : row.Cells["textreturnQuantity"].Value.ToString()));

            cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
        }
    }
}
Appreciate your valuable feedback.

Thank you in advance.

Kind regards,

Andrew
 
Last edited by a moderator:
So which reference was null when the exception was thrown? Find out, find out why and then modify your code accordingly. If you can't work what to do then at least provide us with all the relevant information. You don't just read code to fix issues. You examine it when it's running. That's what debugging is.
 
There are other issues with that code too, but it's not clear the exact nature of them. Did that data come from the database in the first place and how exactly did it get into the grid? Most likely you should be binding a DataTable and using a data adapter to save the changes.
 
Chances are that you don't have a column named "textselectItem" in your dataGridViewDrugReturn.
 
For issues like this, you really need to stop relying on people to do your work for you by running to your favourite forum for help. Don't get me wrong, I am not discouraging you asking for help, but I am discouraging you asking us to do something you should know how to do yourself. And that is knowing how to debug your code. Clearly, you know what error the line bounces and throws a wobbler on, so it makes perfect sense to place a break point on that segment of code of the exact same line where the error occurred, and step through your code. I actually have a debugging tutorial in my signature, which I encourage you to learn from.
 
Back
Top Bottom