简体   繁体   中英

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 in 网格视图 , 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM