Object reference not set to an instance of an object. when binding datatable to datagridview in c #

Viewed 10443

I Want to save multiple value from window form to datatable and then i bind this table to Datagridview. Value are adding in Datatable but At:

dataGridViewX1.DataSource = dt.DefaultView.Table);

binding point error shows

Object reference not set to an instance of an object

How Can I solve it?

public AddOrder(string ItemName,int Qty,Double Price)
    {


        try
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("Item Name");

            dt.Columns.Add("Qty");
            dt.Columns.Add("Unit Price");
            dt.Columns.Add("Amounts");


            DataRow dr = dt.NewRow();
            dr["id"] = a;
            a++;

            dr["Item Name"] = ItemName;
            dr["Qty"] = Qty;
            dr["Unit Price"] = Price;
            dr["Amounts"] = (Convert.ToInt32(dr["Qty"]) * Convert.ToInt32(dr["Unit Price"]));
            dt.Rows.Add(dr);

            dataGridViewX1.DataSource = dt.DefaultView.Table;

        }
        catch(Exception ee)
        {
            DevComponents.DotNetBar.MessageBoxEx.Show(ee.Message,"Error Message");
        }
    }
8 Answers

This error is caused because you are trying to access a property of an object that is null.

Whenever you get this sort of error, you can try to step through and debug your source code. This will help you get to the line that is throwing the error.

You can take a look at which object is null and then fix this error by figuring out why this object is null in your code.

Related