在c#win中的DataTable中动态添加值.形式 [英] Adding Values Dynamically in DataTable in c# win. form
本文介绍了在c#win中的DataTable中动态添加值.形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何插入动态列值?
示例(在固定列号的情况下)
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看起来像(从"TN"开头的所有字段都是动态添加的)
https://www.dropbox.com/s/h3bhk0i0czh0tj0/datatable.png [ ^ ]
在Advance中致谢
DataTable Looks like (All Fields starting from "TN" are dynamically added)
https://www.dropbox.com/s/h3bhk0i0czh0tj0/datatable.png[^]
Thanks in Advance
推荐答案
不知道您未发布的表的数据结构
试试这个
dont know ur data structure of table, which u didn''t posted
try this
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
try
Dt.Rows.Add("Mike",new string [Dt.Columns.Count-2]);
try
Dt.Rows.Add("Mike",new string[Dt.Columns.Count - 2]);
您也可以这样做.....
You can do this way also.....
foreach (DataRow dr in ds.Tables[0].Rows)
{
dr["Name"] = "Mike";
dr["Id"] = 1;
}
这篇关于在c#win中的DataTable中动态添加值.形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文