0

I have two datatables. I want to display them in one Asp: GridView side by side.

Dt1 Col1 co2

Dt2 Col3 col4

I want GridView to display as Col1 col2 col3 col4

There is no relationship with those datatables.

Ramesh
  • 1,041
  • 15
  • 39
  • 1
    Not going to happen – paparazzo Dec 02 '17 at 09:29
  • Ok, let me explain in another way. Is it possible to bind to dt3 then assigning dt3 to GridView possible? – Ramesh Dec 02 '17 at 09:32
  • yes it is possible with `datatable.Merge`. please see this link it is already answered https://stackoverflow.com/questions/285474/merge-2-datatables-and-store-in-a-new-one – Nagib Mahfuz Dec 02 '17 at 09:42
  • DataTable.Merge does not join side by side. In my case it is required to assign two datatables side by side not in append style. – Ramesh Dec 02 '17 at 10:54
  • then go for pivot ...as the example given below – Chandan Kumar Dec 02 '17 at 11:53
  • This thread https://stackoverflow.com/questions/12628020/merging-2-datatables-in-to-1-datatable-with-same-number-of-rows, Cuong Le's answer solved this. – Ramesh Dec 02 '17 at 12:10

2 Answers2

0

You can use pivot table as follows this convert rows as columns

INSERT INTO #yourtable ([Id], [Value], [ColumnName])
VALUES
    (1, 'John', 'FirstName'),
    (2, '2.4', 'Amount'),
    (3, 'ZH1E4A', 'PostalCode'),
    (4, 'Fork', 'LastName'),
    (5, '857685', 'AccountNumber');

SELECT
    Firstname, Amount, PostalCode, LastName, AccountNumber
FROM
    (SELECT
         value, columnname
     FROM
         #yourtable) d
PIVOT
    (MAX(value)
     FOR columnname IN (Firstname, Amount, PostalCode, LastName, AccountNumber)
    ) piv;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
charithsuminda
  • 341
  • 2
  • 9
0

My demo didn't check empty/null validation. If needed, please do.

//Create new class
public class FinalData
{
    public string Col1 { get; set; }
    public string Col2 { get; set; }
    public string Col3 { get; set; }
    public string Col4 { get; set; }

    public FinalData(){}
}

//Populate your two tables into FinalData array as below
int MaxRows = dt1.Rows.Count > dt2.Rows.Count ? dt1.Rows.Count : dt2.Rows.Count;
FinalData[] fdList = new FinalData[MaxRows];

for (int i = 0; i < dt1.Rows.Count; i++)
{
    FinalData[i] = new FinalData() { Col1 = dt1.Rows[i]["Col1"].ToString(), Col2 = dt1.Rows[i]["Col2"].ToString() };
}

for (int i = 0; i < dt2.Rows.Count; i++)
{
    FinalData[i] = new FinalData() { Col3 = dt2.Rows[i]["Col3"].ToString(), Col4 = dt1.Rows[i]["Col4"].ToString() };
}

//Bind your gridview with fdList
YourGridview.DataSource = fdList;
YourGridView.DataBind();
Mike
  • 721
  • 7
  • 13