C# 如何使用for循环拆分数据表行?
我有这样一个数据表: 我想为循环编写一个C# 如何使用for循环拆分数据表行?,c#,datatable,C#,Datatable,我有这样一个数据表: 我想为循环编写一个,在单独的行上显示借方和贷方行,如下所示: 这是我未完成的代码: DataTable dt = new DataTable(); dt.Columns.Add("DEBIT", typeof(string)); dt.Columns.Add("CREDIT", typeof(string)); dt.Columns.Add("AMOUNT", typeof(double)); dt.Rows
,在单独的行上显示借方和贷方行,如下所示:
这是我未完成的代码:
DataTable dt = new DataTable();
dt.Columns.Add("DEBIT", typeof(string));
dt.Columns.Add("CREDIT", typeof(string));
dt.Columns.Add("AMOUNT", typeof(double));
dt.Rows.Add("Debit1", "Credit1", 10);
dt.Rows.Add("Debit2", "Credit2", 8);
dt.Rows.Add("Debit3", "Credit3", 12);
for (int i=1; i <= dt.Rows.Count; i++)
{
//The first image (datatable) has three debit and credit lines are showing on the same line. Normally the debit line and credit line are showing on its own separate lines.
//With above given datatable I want to construct for loop that shows three debit lines and three credit lines as demonstrated in the second image. In this case it shows 6 lines
}
DataTable dt=newdatatable();
添加(“借方”,类型(字符串));
添加(“信用”,类型(字符串));
增加(金额),类型(双);
添加(“借方1”、“贷方1”、10);
增加(“借方2”、“贷方2”、8);
增加(“借方3”,“贷方3”,12);
对于(int i=1;i步骤:
- 以相反的顺序开始循环(这样您就可以轻松地插入行)
- 为信用卡创建一个新行,并用相关数据填充它
- 从原始行中删除信用数据
- 在原始行后面的位置插入新列
像这样的事情应该可以做到:
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
var row = dt.Rows[i];
if (!string.IsNullOrEmpty(row["CREDIT"].ToString()))
{
var creditRow = dt.NewRow();
creditRow["CREDIT"] = row["CREDIT"];
creditRow["AMOUNT"] = row["AMOUNT"];
row["CREDIT"] = string.Empty;
dt.Rows.InsertAt(creditRow, i + 1);
}
}
Hmmm.dt.Rows.Add(“Debit1”和“,”,10);
,dt.Rows.Add(“,”Credit1“,10)
…我猜DataTable中已经填充了数据,并且所讨论的代码仅用于演示。否则,OP应该从一开始就分别填充借方和贷方行。尊敬的41686d6564,非常感谢您的回答。如何显示Console.WriteLine()在与每秒图像相同的for循环中?我不确定您的意思。是否要在控制台中以表格格式打印数据表?如果是,请检查PrintDataTable()
方法。我不确定您为什么要这样做。我只是用它来演示结果。您正在创建控制台应用程序吗?刚刚看到PrintDataTable()。再次感谢您帮助我解决问题。祝您有愉快的一天。