在 C# 中向数据表添加列?

发布于 2024-09-01 06:16:12 字数 1052 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灼痛 2024-09-08 06:16:12

为什么要再次将数据行添加到表中?

删除行 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

归途 2024-09-08 06:16:12

使用 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文