如何将数据添加到数据表 [英] How to add data to datatable

查看:48
本文介绍了如何将数据添加到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c#中的循环内将数据添加到数据表中,但我不能.我使用此代码,但它不会运行1次.当 i = 2 时,它不起作用.请帮忙.

I want to add data to datatable within a loop in c# but I cannot. I use this code but it runs 1 time not more. When i=2 it dose not work. Please help.

DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = dt.NewRow();

for (int i = 0; i < 10; i++)
{
    dr["ProductId"] = i.ToString();
    dr["ProductTotalPrice"] = (i*1000).ToString();
    dt.Rows.Add(dr);
}

推荐答案

这是因为您仅在外部循环中创建了一个 DataRow ,因此实际上您在用新的写代码覆盖了该行中的旧值..您的行创建应该在循环内,因此每次迭代都会有新行,例如

That's cause you are creating only one DataRow outside loop and so you are actually over writing the old values in that row with new one's. Your row creation should be inside loop and thus you will have new row per iteration like

DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = null;

for (int i = 0; i < 10; i++)
{
    dr = dt.NewRow(); // have new row on each iteration
    dr["ProductId"] = i.ToString();
    dr["ProductTotalPrice"] = (i*1000).ToString();
    dt.Rows.Add(dr);
}

这篇关于如何将数据添加到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆