如何在GridView中使用DataBinder.Eval?

问题描述 投票:0回答:2

我有一个包含标签的GridView,我需要根据数据显示/隐藏标签。

这是我的 GridView:

<asp:GridView ID="GridView_Profiles" runat="server" CssClass="grid" HorizontalAlign="Center"
                                        OnRowDataBound="GridView_Profiles_OnRowDataBound" CellSpacing="1" GridLines="None"
                                        AutoGenerateColumns="False" Width="90%">
    <Columns>
      <asp:Label ID="Label_SelectedCount" runat="server"> 
        <span style="width:auto;color:White;background-color:#0c95be;height:auto;margin:0px;font-size:12px;cursor:pointer;padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px;">
          <%#Eval("Count") %>
        </span>
      </asp:Label>
     <asp:Label ID="lblNoCount" runat="server" Text="-"></asp:Label>
    </Columns>
</asp:GridView>

在上面的 GridView

RowDataBound
中,我应该如何使用
DataBinder.Eval
检查边界数据?

c# asp.net gridview
2个回答
0
投票

使用它来获取 RowDataBound 事件中的标签

DataBinder.Eval
:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // find your label text in gridview with DataBinder.Eval
        string count = DataBinder.Eval(e.Row.DataItem, "Count") as string;

        // find your label control in gridview
        Label lb = (Label)e.Row.FindControl("Label_SelectedCount");

        // check condition to show/hide label (you use your own condition)
        if(count > 0)
            lb.Visible = true;
        else
            lb.Visible = false;

    }
}

或者您可以将 GridView 与

DataBinder.Eval
绑定,例如:

<asp:TemplateField HeaderText="Count"
    <ItemTemplate>
        <asp:Label ID="Label_SelectedCount" runat="server" >
            <%# DataBinder.Eval(Container.DataItem, "Count")%>
        </asp:Label>
    </ItemTemplate>
</asp:TemplateField>

注意: 您还可以将数据绑定到 Label 的 Text 属性,如下所示

Text='<%#Eval("Count") %>'


0
投票

我使用 ToString() 因为当数据不是字符串时我得到“null”

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string count = DataBinder.Eval(e.Row.DataItem, "Count").ToString();
        
        Label LabelCount = (Label)e.Row.FindControl("Label_SelectedCount");
        
        if((int)count > 0)
            LabelCount .Visible = true;
        else
            LabelCount .Visible = false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.