Click here to Skip to main content
15,896,527 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i am trying to add new row in dataset for table already created in dataset with name retired ,
i get below error:
Object reference not set to an instance of an object.

any idea please?

What I have tried:

 DataRow dr = ds.Tables["retired"].NewRow();
                   dr["Empno"] = empno.Text;
                   dr["Empname"] = name.Text;
                   dr["Formno"] = formon.Text ;
                   dr["x1"] = "X";
ds.Tables["retired"].Rows.Add(dr);
Posted
Updated 8-Feb-17 4:15am
Comments
Michael_Davies 8-Feb-17 7:00am    
Which line?
loai_maane 19-Feb-17 6:03am    
first line, i already create data table with same name retired
ZurdoDev 8-Feb-17 7:12am    
No idea, because you did not tell us which line of code caused it. But the error is saying something doesn't exist that you are trying to access. Just fix it.

Without more info, I can only guess that it might be that the table "retired" does not exist in the Tables collection.
 
Share this answer
 
First Thing First . replace ds.Tables["retired"].NewRow(); with ds.Tables[0].NewRow(). Dont give table name . Give Table ID. And it will solve your issue.

Example For you
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("name",typeof(string));
DataRow dr = dt.NewRow();
dr["ID"] = "1";
dr["name"] = "Chaueby";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
//from Here your Solution Start
DataRow dr1 = ds.Tables[0].NewRow();
dr1["ID"] = "Chaubey1";
dr1["name"] = "Chaubasdasdey1";
ds.Tables[0].Rows.Add(dr1);
Your solution should be like this. . NO Table Name
 
Share this answer
 
v2
Comments
loai_maane 19-Feb-17 6:22am    
Dear,
sorry today i try your solution it give error Cannot find table 0, i already create data table with name retired
public partial class Class1 : Page
{
DataSet ds = null;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds2 = GetDataSet();

DataTable dt2 = ds.Tables["retired"];
DataRow dr = dt2.NewRow();
dr["Empno"] = "2";
dr["Empname"] = "Aa";
dr["Formno"] = "Bb";

dt2.Rows.Add(dr);
ds.Tables.Remove("retired");
ds.Tables.Add(dt2);
}

public DataSet GetDataSet()
{
ds = new DataSet();
DataTable dt = new DataTable("retired");
dt.Columns.Add("Empno");
dt.Columns.Add("Empname");
dt.Columns.Add("Formno");

DataRow dr = dt.NewRow();
dr["Empno"] = "1";
dr["Empname"] = "A";
dr["Formno"] = "B";

dt.Rows.Add(dr);
ds.Tables.Add(dt);
return ds;
}
}
Check this code if it may help you.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900