Rami Far
Rami Far

Reputation: 404

Gridview null reference exception c#

I am adding data in gridview on button click event through following code:

            int row = 0;
            dataGridView1.Rows.Add();
            row = dataGridView1.Rows.Count - 2;
            dataGridView1["Description",row].Value = name;
            dataGridView1["Quantity", row].Value = qty.Text;
            dataGridView1["Price", row].Value = p;
            dataGridView1["Discountcell", row].Value = "0000";
            dataGridView1["amt", row].Value = tot;

its working perfectly fine. now i want when I enter discount ingridview, discount should minus from total amount. for this I have following code:

foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                int n = item.Index;
               dataGridView1["amt", n].Value = tot - float.Parse(dataGridView1.Rows[n].Cells[3].Value.ToString());
            }

Here it gives me following error:

An unhandled exception of type 'System.NullReferenceException' occurred in Sales System1.exe

Additional information: Object reference not set to an instance of an object.

without this subtracting code data is added in gridview. but when I put this code it gives above error. What I need to do?

Upvotes: 0

Views: 683

Answers (2)

Omar Muscatello
Omar Muscatello

Reputation: 1301

Since you have the AllowUserToAddRows setted to true, the dataGridView1.Rows includes the editor row in the list of rows.

Infact, the last value assigned to the item variable in the foreach cycle is exactly that row (editor row). If you don't want to set the AllowUserToAddRows to false you can skip processing that row using the IsNewRow property of the row itself.

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (item.IsNewRow) break;
    dataGridView1["amt", item.Index].Value = tot - float.Parse(item.Cells["Discountcell"].Value.ToString());
}

Upvotes: 1

Sami
Sami

Reputation: 2110

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    float f;
    int n = item.Index;
    if (float.TryParse(dataGridView1.Rows[n].Cells[3].Value.ToString(), out f))
    {
         dataGridView1["amt", n].Value = tot - f;
    }
}

Upvotes: 1

Related Questions