0

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?

9
  • What is tot?? is it define somewhere? Commented Apr 6, 2017 at 5:24
  • tot is amount which I am getting from multiplying price to quantity Commented Apr 6, 2017 at 5:25
  • Do a null check on the cell value or use TryParse. Commented Apr 6, 2017 at 5:31
  • Can you check what element is null at where this exception is thrown Commented Apr 6, 2017 at 5:32
  • @ReadyFreddy how can I check tell me? Commented Apr 6, 2017 at 5:32

2 Answers 2

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Sir error is because it go on next row also which is not yet added, because editing is enabled. now please tell me which I do to no have this error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.