1

在 Web 应用程序中,我正在尝试绑定 gridivew 的标题模板,但我无法将数据绑定到 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>
4

2 回答 2

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";
    }
于 2013-05-29T11:36:57.843 回答
0

如果您想将 DataTable 列标题绑定到 Gridview 标题,另一种相当简单的方法(例如,您正在生成列名可以不同的 DataTable,并且您希望这些动态名称是 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 = ... 对页脚行执行相同的操作

于 2021-04-03T14:51:33.973 回答