如何从数据表中反转行列并在asp.net中显示到gridview

时间:2016-04-02 19:34:14

标签: c# asp.net gridview

我有一个名为test的数据表,其中包含如下所示的值

Firstname  Lastname   Age   Location
Sasi       verpal     30    Veega

我想在gridview中显示它,如下所示

Firstname    sasi
Lastname    verpal  
Age           30    
Location     Veega

如何实现它?

1 个答案:

答案 0 :(得分:1)

您可以通过将列名和值移动到其他结构(类),然后将该类的列表绑定到网格来解决此问题。

void Main()
{   
    List<DisplayColumn> dataList = new List<DisplayColumn>();
    dataList.Add(new DisplayColumn("Firstname", "Sasi"));
    dataList.Add(new DisplayColumn("Lastname", "verpal"));
    dataList.Add(new DisplayColumn("Age", "30"));
    dataList.Add(new DisplayColumn("Location", "Veega"));

    // However, in your case you can add the values using
    foreach (var column in myTable.Rows[0].Columns)
    {
        dataList.Add(new Tuple<string, string>(column.Name, column.Value.ToString()));
    }

    // Now bind the dataList to your grid
}

public class DisplayColumn
{
    public string ColumnName { get; set; }
    public string ColumnValue { get; set; }

    public DisplayColumn(string columnName, string columnValue)
    {
        ColumnName = columnName;
        ColumnValue = columnName;
    }
}