How to split DataTable rows using a for loop?

Viewed 278

I have a DataTable like this:

Original DataTable

And I want to write a for loop that shows debit and credit line on its own separate line like this:

Result

Here is my unfinished code:

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
}

I would much appreciate it if you could help me with this.

1 Answers

Steps:

  • Start the loop in reverse (so you can easily insert rows).
  • Create a new row for the credit and fill it with the relevant data.
  • Remove the credit data from the original row.
  • Insert the new column in the position following the original row.

Something like this should do the trick:

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);
    }
}

Try it online.

Related