如何使用C#将第一个数据表中的数据添加到第二个数据表的新列 [英] How to add new column with data from first data table to second data table using C#
本文介绍了如何使用C#将第一个数据表中的数据添加到第二个数据表的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在表格中的当前结果[0]
My Current Result in Table[0]
Id | Name | City
1 | Akshada | Baroda
2 | Rutu | Pune
我想将Table [2]中的Cast添加到表[0]中
我想要以下答案
I want to add Cast from Table[2] into Table[0]
I Want Below Answer
Id | Name | City | Cast
1 | Akshada | Baroda | Bramhin
2 | Rutu | Pune | Rajput
3 | Priya | Jaipur | Muslim
我想使用foreach循环添加Cast
检查下表中的我的数据例如
I Want to add Cast using foreach loop
Check My DATA in Below Tables for Example
----------
表[0]
Table[0]
Id | Name | City
1 | Akshada | Baroda
2 | Rutu | Pune
3 | Priya | Jaipur
----------
表[2 ]
Table [2]
Bramhin
Rajput
Muslim
----------
我的尝试:
What I have tried:
objResult = objDataBl.Result_SelectAll_ForDisplay(intBatchId);
objResult.ResutlDs.Tables[0].Columns.Add("Cast", typeof(string));
foreach (DataRow row in objResult.ResutlDs.Tables[0].Rows)
{
row["Cast"] = objResult.ResutlDs.Tables[2].Rows[0]["Column1"].ToString();
}
使用上面的代码我错了ans
我的答案是
Using above code i got wrong ans
My Answer is
Id | Name | City | Cast
1 | Akshada | Baroda | Bramhin
2 | Rutu | Pune | Bramhin
3 | Priya | Jaipur | Bramhin
推荐答案
简单:每次停止使用行零:
Simple: stop using row zero each time:
row["Cast"] = objResult.ResutlDs.Tables[2].Rows[0]["Column1"].ToString();
^
|
相反,在循环外设置一个整数变量(或者更好地使用代替
循环而不是 foreach
)并使用它代替常量值。
Instead, set up a integer variable outside your loop (or better use a for
loop instead of a foreach
) and use that instead of the constant value.
Thank you all for helping me i got solution using below code
objResult.ResutlDs.Tables[0].Columns.Add("Cast", typeof(string));
for (int i = 0; i < objResult.ResutlDs.Tables[0].Rows.Count; i++)
{
objResult.ResutlDs.Tables[0].Rows[i]["Cast"] = objResult.ResutlDs.Tables[2].Rows[i]["Cast"];
}
这篇关于如何使用C#将第一个数据表中的数据添加到第二个数据表的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文