Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
How to inserted dynamic column value's?

Example (in the case of fixed column number)
Dt.Columns.Add("Name");
Dt.Columns.Add(""Id"");

Dt.Rows.Add("Mike",1);

Example (in the case of dynamic column number)
//Column count are not fixed come according to records inserted in database

Dt.Rows.Add("Mike",1);//How to add the column's value in Rows.Add dynamically

I Tried
Dt.Rows.Add(new string[Dt.Columns.Count - 2],"Mike",1);

but wasn't successful. Can Somebody help me here.

Error on writing the above code
Unable to cast object of type 'System.string[]' to type 'System.IConvertible'.Couldn't store <System.string[]> in TN5 Column.  Expected type is string.


DataTable Looks like (All Fields starting from "TN" are dynamically added)
https://www.dropbox.com/s/h3bhk0i0czh0tj0/datatable.png[^]

Thanks in Advance
Posted
Updated 10-Mar-14 1:17am
v4
Comments
george4986 10-Mar-14 7:01am    
can u post the structure of datatable and required output

dont know ur data structure of table, which u didn't posted

try this

C#
  string colName = "name from database ";
 /////more than one columns take the count
DataTable dt1 = new DataTable();
/////more than one column case use below code inside a loop with count of columns
  dt1.Columns.Add(colName, typeof(string));
////////////add new row after adding columns
 DataRow dr1 = dt1.NewRow();
  dr1[colName] = "value";
 dt1.Rows.Add(dr1.ItemArray);


gud luck
 
Share this answer
 
v2
Comments
agent_kruger 10-Mar-14 7:38am    
sir, actually i posted the image.
george4986 10-Mar-14 7:49am    
does the above code working?
agent_kruger 10-Mar-14 7:57am    
thank you sir, it just worked fine.
george4986 10-Mar-14 7:54am    
sorry dropbox is blocked here ;-(
agent_kruger 10-Mar-14 7:57am    
no problem sir it worked.
try

Dt.Rows.Add("Mike",new string[Dt.Columns.Count - 2]);
 
Share this answer
 
Comments
agent_kruger 10-Mar-14 7:12am    
sir, in the question i have mentioned the same solution which did not work.
You can do this way also.....

C#
foreach (DataRow dr in ds.Tables[0].Rows)
{

    dr["Name"] = "Mike";
    dr["Id"] = 1;

}
 
Share this answer
 
Comments
agent_kruger 10-Mar-14 7:13am    
sir, i am trying to add rows not update the existing one.

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