这是论坛某位仁兄贴的代码,问下怎样动态添加列??
原帖地址:http://topic.csdn.net/u/20100821/15/b59b7931-5675-4510-a1f9-6b40d2fa1817.htmlstring[] str1 = { "红色", "黑色" };
string[] str2 = { "L", "M" };
DataTable dt = new DataTable();
DataColumn col = new DataColumn("颜色", typeof(string));
dt.Columns.Add(col);
col = new DataColumn("尺寸", typeof(string));
dt.Columns.Add(col);
col = new DataColumn("库存", typeof(int));
dt.Columns.Add(col);
DataRow dr;
int storeCount = 1; //用来保存库存号
for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
dr = dt.NewRow();
dr["颜色"] = str1[i];
dr["尺寸"] = str2[j];
dr["库存"] = storeCount;
dt.Rows.Add(dr);
storeCount++;
}
}
}
string[]也是动态的,如果这样写,for循环个数也是动态,这可如何是好
--------------------编程问答-------------------- 动态就是未知,难道lz想咋样? --------------------编程问答-------------------- 不知道为什么要动态添加呢 如果动态添加 起码有个数据来源, 照着数据源生成 datatable --------------------编程问答-------------------- 这里只有颜色列str1,尺码列str2
但我的需求是这些列个数也是未知的 --------------------编程问答-------------------- 动态添加已经有了,楼主是想说table结构动态的吧,这好像没多大问题吧
循环动态的数据源添加列就行了 --------------------编程问答--------------------
string[] strCols = { "颜色", "尺寸", "库存" };--------------------编程问答-------------------- 列个数未知,那就循环这部分
string[] str1 = { "红色", "黑色" };
string[] str2 = { "L", "M" };
DataTable dt = new DataTable();
foreach (string strC in strCols) {
DataColumn col = new DataColumn(strC, typeof(string));
dt.Columns.Add(col);
}
DataRow dr;
int storeCount = 1; //用来保存库存号
int rows = str1.Length > str2.Length ? str2.Length : str1.Length;
for (int i = 0; i < rows; i++) {
dr = dt.NewRow();
//for (int c = 0; c < dt.Columns.Count; c++) {
dr[0] = str1[i];
dr[1] = str2[i];
//}
}
DataColumn col = new DataColumn("颜色", typeof(string));
dt.Columns.Add(col);
--------------------编程问答-------------------- 没懂 不已经是了吗 --------------------编程问答--------------------
string[] strCols = { "颜色", "尺寸", "库存" };
string[] str1 = { "红色", "黑色" };
string[] str2 = { "L", "M" };
System.Data.DataTable dt = new System.Data.DataTable();
foreach (string strC in strCols) {
System.Data.DataColumn col = new System.Data.DataColumn(strC, typeof(string));
dt.Columns.Add(col);
}
System.Data.DataRow dr;
int storeCount = 1; //用来保存库存号
int rows = str1.Length > str2.Length ? str2.Length : str1.Length;
for (int i = 0; i < rows; i++) {
dr = dt.NewRow();
//for (int c = 0; c < dt.Columns.Count; c++) {
dr[0] = str1[i];
dr[1] = str2[i];
dt.Rows.Add(dr);
//}
}
输出
dt.Rows[0].ItemArray
{object[3]}
[0]: "红色"
[1]: "L"
[2]: {}
dt.Rows[1].ItemArray
{object[3]}
[0]: "黑色"
[1]: "M"
[2]: {} --------------------编程问答--------------------
列头遍历出来了,那列内容呢 --------------------编程问答-------------------- 如果列的个数已知,大家有不有办法
颜色:红色 黑色 白色 黄色
尺寸:L M
重量:10 20 30
--------------------编程问答-------------------- 动态生成数据表大概就是那样搞了.
补充:.NET技术 , ASP.NET