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

I want to save several values ​​from a window form into a datatable , and then bind this table to a Datagridview . The value is added to Datatable, but At:

dataGridViewX1.DataSource = dt.DefaultView.Table);

anchor point error shows

Object reference not set to object instance

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");
        }
    }
+4
source share
7 answers

Directly assign data table gridview:

dataGridViewX1.DataSource = dt;

instead:

dataGridViewX1.DataSource = dt.DefaultView.Table;
+1
source

is dataGridViewX1 initialization in the InitializeComponent method?

    I Think it is parameterized constructor I it does not has initialization of controls

1) solution

   InitializeComponent(); need to call this method.

+1

,

- dr["Qty"] = Qty;

 - dr["Unit Price"] = Price;

, .

 - dr["Qty"] = 3;

  - dr["Unit Price"] = 4;
0

, , .

, (a):

    AddOrder("something", 2, 100);  
    ...
    //assign some default value since the PO did not define the variable at all...
    int a=0;

:

        dt.Columns.Add("Qty",typeof(int));
        dt.Columns.Add("Unit Price",typeof(Decimal));
        dt.Columns.Add("Amounts",typeof(Decimal));

, , :

dt.Columns.Add("Amount", typeof(Decimal), "Qty *[Unit Price]");

Update:

, , :

dataGridViewX1.DataSource = null;
dataGridViewX1.DataSource = dt.DefaultView;
0
private void BindDataGrid()
{
    DataTable table = new DataTable();

    // Insert code to populate a DataTable with data. 

    // Bind grid to DataTable.
    dataGrid1.DataSource = table;
}
0

dataGridViewX1.DataSource = dt;

dt.

0

, . , , datagrid - :

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound"

When you call GridView1.DataBind(), the method GridView1_RowDataBoundis executed for each row during the data binding process. This method may contain incorrect code to give you an "object reference ..." exception.

0
source

All Articles