1

I have a DataGridView that is being filled with DataTable → Fill() method.

I want to add another Table in the same DataGridView, in the next column, just when the other one ends. Is it possible?

Now I have something like this

da.Fill(dt);
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.DataSource = dt;

I want to add another DataTable to the same DataGridView in new columns. Thanks

Juanma
  • 31
  • 6
  • 1
    Combine [two DataTables into one](https://stackoverflow.com/questions/33543244/combining-two-c-sharp-datatables-into-one)? – icebat Jul 06 '18 at 12:15
  • The most natural way is to write a join to create the result in the first place.. – TaW Jul 06 '18 at 12:49

1 Answers1

0

Use the Merge function of DataTable and then shift elements up. See codes below:

private void AddTwoDataTable()
{
    DataTable dt1 = new DataTable();
    dt1.Columns.Add("ID1", typeof(int));
    dt1.Columns.Add("Value1", typeof(string));
    dt1.Columns.Add("Value2", typeof(string));

    DataTable dt2 = new DataTable();
    dt2.Columns.Add("ID2", typeof(int));
    dt2.Columns.Add("Value3", typeof(string));

    dt1.Rows.Add(new object[] { 1, "a", "ab"});
    dt1.Rows.Add(new object[] { 2, "b", "bc" });
    dt1.Rows.Add(new object[] { 3, "c", "cd" });
    dt1.Rows.Add(new object[] { 4, "d", "de" });

    dt2.Rows.Add(new object[] { 101, "x" });
    dt2.Rows.Add(new object[] { 102, "y" });
    dt2.Rows.Add(new object[] { 103, "y" });

    var newtable = MergetwoTables( dt1, dt2 );
    dataGridView1.DataSource = newtable;
}

public static DataTable MergetwoTables(DataTable dt1, DataTable dt2)
{
    DataTable table = new DataTable("NewTable");

    table.Merge(dt1);
    table.Merge(dt2);

    int maxRows1 = dt1.Rows.Count;
    int maxColu1 = dt1.Columns.Count;
    int maxRows2 = dt2.Rows.Count;
    int maxColu2 = dt2.Columns.Count;

    // copy elements from new rows
    for (int r = maxRows1; r < maxRows1 + maxRows2; r++)
        for (int c = maxColu1; c < maxColu1 + maxColu2; c++)
            table.Rows[r - maxRows1][c] = table.Rows[r][c];

    //delete new rows
    var maxrows = maxRows1 > maxRows2 ? maxRows1 : maxRows2;
    for (int r = maxRows1 + maxRows2 - 1; r >= maxrows; r--)
        table.Rows[r].Delete();

    return table;
}

Output:

enter image description here

L_J
  • 2,351
  • 10
  • 23
  • 28
  • Thank you, at the end it seems it didn't work, but I apreciate it. – Juanma Jul 09 '18 at 11:57
  • @Juanma Can you provide an example when it didn't work? – L_J Jul 09 '18 at 12:04
  • I just realized that if rows count of the second table exceeds rows count for the first table this would lose some rows from the second table. Now, I fixed it. – L_J Jul 09 '18 at 12:54
  • Nice, thank you so much, I'll leave it a try tomorrow and I'll tell you! – Juanma Jul 18 '18 at 11:50