在 C# 中向数据表添加列?
我有一个 csv 阅读器类,它读取 .csv
文件及其值...我已经用它创建了 datatable
...考虑我的 Datatable< /code> 包含三个标题列
Name,EmailId,PhoneNo
...值已成功添加...现在我想添加两列 IsDeleted,CreatedDate
到这个数据表
...我已经尝试过这个,但它似乎不起作用,
foreach (string strHeader in headers)
{
dt.Columns.Add(strHeader);
}
string[] data;
while ((data = reader.GetCSVLine()) != null)
{
dt.Rows.Add(data);
}
dt.Columns.Add("IsDeleted", typeof(byte));
dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
foreach (DataRow dr in dt.Rows)
{
dr["IsDeleted"] = Convert.ToByte(0);
dr["CreatedDate"] = Convert.ToDateTime(System.DateTime.Now.ToString());
dt.Rows.Add(dr);
}
dt.Rows.Add(dr);
显示一个错误,说This行已经属于该表。
....
替代文本 http://www.imagechicken.com/uploads/ 1273560975016964800.jpg
I have a csv reader class that reads a .csv
file and its values.... I have created datatable
out of it... Consider my Datatable
contains three header columns Name,EmailId,PhoneNo
.... The values have been added successfully.... Now i want to add two columns IsDeleted,CreatedDate
to this datatable
... I have tried this but it doesn't seem to work,
foreach (string strHeader in headers)
{
dt.Columns.Add(strHeader);
}
string[] data;
while ((data = reader.GetCSVLine()) != null)
{
dt.Rows.Add(data);
}
dt.Columns.Add("IsDeleted", typeof(byte));
dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
foreach (DataRow dr in dt.Rows)
{
dr["IsDeleted"] = Convert.ToByte(0);
dr["CreatedDate"] = Convert.ToDateTime(System.DateTime.Now.ToString());
dt.Rows.Add(dr);
}
dt.Rows.Add(dr);
shows an error saying This row already belongs to this table.
....
alt text http://www.imagechicken.com/uploads/1273560975016964800.jpg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要再次将数据行添加到表中?
删除行
dt.Rows.Add(dr);
并直接编辑数据表,如下所示
dt.Rows[i]["IsDeleted"] = Convert.ToByte(0);
代码> 使用 for 循环Why do you add the datarow again into the table?
Remove the line
dt.Rows.Add(dr);
and edit the datatable directly like this
dt.Rows[i]["IsDeleted"] = Convert.ToByte(0);
using a for loop使用 dt.Rows.Import 或 dt.ImportRows,我忘记了名称
或从您的代码判断,为什么需要 dt.Rows.Add?不应该省略吗?
Use dt.Rows.Import, or dt.ImportRows, I forgot the name
or judging from your code, why you need the dt.Rows.Add? shouldn't that be omitted?