将数据绑定到Gridview标题模板?在Asp.net

时间:2012-06-17 17:02:49

标签: asp.net

在Web应用程序中,我试图绑定gridview的Header Template,但我无法将数据绑定到gridview头。

   <asp:GridView ID ="grdInner" runat ="server" AutoGenerateColumns ="false" >
       <Columns >
          <asp:TemplateField >
             <HeaderTemplate >
          <asp:Label ID="lblHeader" runat="server" Text='<%# Eval("title") %>'></asp:Label>     
              </HeaderTemplate>
              <ItemTemplate >
                 <asp:Label ID ="lblDesc" runat ="server" Text ='<%# Eval("description") %>'></asp:Label>
              </ItemTemplate>
          </asp:TemplateField> 
       </Columns>
     </asp:GridView>

2 个答案:

答案 0 :(得分:4)

以下代码实现相同的目标

<asp:GridView runat="server" ID="gridView" onrowdatabound="gridView_OnRowDataBound" AutoGenerateColumns="false">
<columns>
    <asp:TemplateField>
        <HeaderTemplate><asp:Label runat="server" ID="lblHeader"></asp:Label></HeaderTemplate>
    </asp:TemplateField>
</columns>
</asp:GridView>

您可以在OnRowDataBound事件中设置标签文本

 protected void gridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
            ((Label)e.Row.FindControl("lblHeader") as Label).Text = "Your Data here";
    }

答案 1 :(得分:0)

如果您想将 DataTable 列标题绑定到 Gridview 标题(例如,您正在生成列名可以不同的数据表,并且您希望这些动态名称成为 GridView标题列名称)。

DataTable dt = // Call your DataTable here.

    // Get your column names here.
    string nutrient = dt.Columns[2].ColumnName;
    string nutrient1 = dt.Columns[3].ColumnName;
    string nutrient2 = dt.Columns[4].ColumnName;
    string nutrient3 = dt.Columns[5].ColumnName;
    string nutrient4 = dt.Columns[6].ColumnName;
    string nutrient5 = dt.Columns[7].ColumnName;
    
    GridView1.DataSource = dt;
    GridView1.DataBind();

    if (GridView1.Rows.Count > 0)
    {
        GridView1.HeaderRow.Cells[2].Text = nutrient;
        GridView1.HeaderRow.Cells[3].Text = nutrient1; 
        GridView1.HeaderRow.Cells[4].Text = nutrient2;
        GridView1.HeaderRow.Cells[5].Text = nutrient3;
        GridView1.HeaderRow.Cells[6].Text = nutrient4;
        GridView1.HeaderRow.Cells[7].Text = nutrient5;            
    } 

您也可以使用 GridView1.FooterRow.Cells[x].Text = ...

对页脚行执行相同的操作