如何在GridView中使用DataBinder.Eval?

时间:2017-09-13 09:50:35

标签: c# asp.net gridview

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

这是我的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检查边界数据?

1 个答案:

答案 0 :(得分:0)

使用此选项可以使用DataBinder.Eval

在RowDataBound事件中获取Label
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") %>'