如何将两个C#数据表绑定到一个ASP:GridView

时间:2017-12-02 09:27:08

标签: c# sql asp.net

我有两个数据表。我想在一个Asp:GridView中并排显示它们。

DT1 Col1 co2

DT2 Col3 col4

我希望GridView显示为 Col1 col2 col3 col4

与这些数据表无关。

2 个答案:

答案 0 :(得分:0)

您可以按如下方式使用数据透视表,将行转换为列

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;

答案 1 :(得分:0)

我的演示没有检查空/空验证。如果需要,请做。

//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();