Object reference not set to an instance of an object. when binding datatable to datagridview in c #
10,043
Solution 1
The object reference exception could be occurring in an event handler related to data binding. For example, let's say your datagrid has something like this in the markup:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound"
When you call GridView1.DataBind()
, the GridView1_RowDataBound
method executes for each row during the data bind process. This method could contain some bad code to give you the "object reference..." exception.
Solution 2
is the initialization of the dataGridViewX1 in a InitializeComponent method?
I Think it is parameterized constructor I it does not has initialization of controls
1) solution
InitializeComponent(); need to call this method.
Its working my application
Related videos on Youtube
Author by
ziakhan
Updated on June 26, 2022Comments
-
ziakhan almost 2 years
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"); } }
-
Nitin Varpe over 10 yearshave u tried dataGridViewX1.DataSource = dt;
-
-
ziakhan over 10 yearsThanks for reply i this code (dataGridViewX1.DataSource = dt;) but still same problem
-
ziakhan over 10 yearsThanks for reply i this code (dataGridViewX1.DataSource = dt;) but still same problem
-
NoChance over 10 yearsWhat problem? Please give specific error. Do you get an exception? What is the exception message?
-
ziakhan over 10 yearsexception message :Object reference not set to an instance of an object
-
NoChance over 10 yearsthis is strange, try to see update in answer...Also, do a debug trace and see if dt is null or not before the bind.
-
Shaharyar over 10 yearsUpdate your question with the stack trace of exception
-
ziakhan over 10 yearsOne record is exist in dt, but when i bind it ti datagridviewx1 then it cause the error Object reference not set to an instance of an object
-
ziakhan over 10 yearsYes dear Method and datagridview are on the form
-
ziakhan over 10 yearsdt is not null it has one record
-
NoChance over 10 yearsThis is very strange. I almost can't imagine that you get a bind error this way. Maybe you are not using standard datagridview component...