Click here to Skip to main content
12,396,047 members (65,326 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# C#4.0
Hi, i use below code to add new row to my datagridview which has a dataset as datasource.it gives an error saying "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound" when i use
datagridview1.Rows.Add()
. So i searched on internet found below solution.But now it gives an NullReferenceException saying "Object reference not set to an instance of an object."


// ds_ITEMS is my dataset name.
DataRow dr = ds_ITEMS.Tables["StkTrx"].NewRow(); // NullReferenceException gives in this line
            dr["Code"] = this.txtCode.Text;
            dr["ItemDes"] = this.txtDes.Text;
            dr["Qty"] = this.txtQty.Text;
            dr["UnitPrice"] = this.txtCostPrice.Text;
            dr["Amount"] = this.txtAmount.Text;
 
            ds_ITEMS.Tables["StkTrx"].Rows.Add(dr);

Any suggestions?
Posted 14-Dec-12 3:02am
Updated 14-Dec-12 3:26am
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

The null reference exception is because the dataSet'ds_ITEMS' is not loaded with any tables. The ds_ITEMS.Tables.Count might be zero and there is no such table with the name 'StkTrx".

Double check your dataSet preparation is done as expected and if you are using database queries to fill up the dataset check the sql statement and the table name it returns matches the name StkTrx.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 14 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100