如何将行值作为列标题

时间:2011-07-18 17:45:44

标签: c# asp.net

我遇到了网格视图的问题,因为我是asp.net的新手(10天),所以我不知道怎么做,所以你可以帮我解决这个问题..

我有一个简单的gridview,我必须创建一个新的网格,其行值为列标题名称

Empname Earnngs Amount

Austin HRA 20,000 $

Austin DA 1,000 $

Austin Basic 5,000 $

我必须这样做

.Austin HRA DA BASIC

    2000$ 2000$ 2000$

请使用C#来提供一些想法和一些示例

3 个答案:

答案 0 :(得分:2)

以下是使用asp GridView执行此操作的示例:

// Create new DataTable.
DataTable dt = new DataTable();

// Total count of columns.
int colCount = 3;

// Add 3 columns.
for (int i = 0; i < colCount; i++)
{
    dt.Columns.Add(new DataColumn("col" + i.ToString()));
}

// Add data to the datatable.
dt.Rows.Add(new object[] { "Empname", "Earnngs", "Amount" });
dt.Rows.Add(new object[] { "Austin", "Earnngs", "Amount" });
dt.Rows.Add(new object[] { "Austin", "df", "Amount" });
dt.Rows.Add(new object[] { "sdfsdf", "dsfdf", "df" });
dt.Rows.Add(new object[] { "Empdsfsdfname", "Earnngs", "df" });

// Loop through each column in the DataTable and set the column name to the data in the first row of data.
foreach (DataColumn dc in dt.Columns)
{
    dc.ColumnName = dt.Rows[0][dc].ToString();
}

// Set the datasource of the grid.
this.GridView1.DataSource = dt;

// Bind the data to the grid.
this.GridView1.DataBind();

见这些:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview(v=VS.100).aspx

http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

http://msdn.microsoft.com/en-us/library/system.data.datacolumn.aspx

答案 1 :(得分:0)

奇怪。但是,使用第一行值创建DataTable作为dataColumn名称,其余数据将作为数据行。将此表绑定到网格。

答案 2 :(得分:0)

如果有人遇到这种问题,你可以参考这个编码

SqlCommand cmd = new SqlCommand("Your query", con);
            SqlDataReader rdr;
            rdr = cmd.ExecuteReader();

            DataTable dt = new DataTable();

            DataRow newRow = dt.NewRow();


            DataColumn dc = new DataColumn();


            rdr.Read();
            dt.Columns.Add(new DataColumn(rdr[Index].ToString()));
            rdr.Close();

            rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {

                dt.Columns.Add(new DataColumn(rdr[Index].ToString()));
            }

            rdr.Close();
            rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                string Amount = rdr[Index].ToString();
                string EarnName = rdr[Index].ToString();
                newRow[EarnName] = Amount;


            }
            dt.Rows.Add(newRow);

            GridView1.DataSource = dt;
            GridView1.DataBind();

DownLoad Torrent at High Speed