Evaluate datafield on boundfield to display text accordingly

▼魔方 西西 提交于 2019-12-23 12:37:31

问题


Hello everyone How can I display different strings in boundfield according to value from datafield?

For instance, if datafield has a value of 1, it should display "Pending". If 2, "Deleted".

Thanks in advance.


回答1:


You can use server side function to display conditional value.

Take a look at this sample:

         <asp:TemplateField ItemStyle-CssClass="TemplateFieldOneColumn">
            <ItemTemplate>
                <asp:Label runat="server" Text='<% #GetLabelText(Eval("status")) %>' />
            </ItemTemplate>
         </asp:TemplateField>

Here is server side function declared on hosting page:

    public string GetLabelText(object dataItem)
    {
        string text = "";
        int? val = dataItem as int?;
        switch (val)
        {
            case 1:
                text = "Pending";
                break;
            case 2:
                text = "Deleted";
                break;

        }
        return text;
    }



回答2:


Use a TemplateField, and not a BoundField. Then add an event to the GridView for RowDataBound. In the method called, you'll evaluate your value (stored in a hidden field in the example below) and output the appropriate text (to Label in the example).

Here's a little bit of starter code.

<ItemTemplate>
  <asp:HiddenField ID="hdnStatus" runat="server" Value='<%# Bind("status") %>' />
  <asp:Label ID="lblStatus" runat="server" />
</ItemTemplate>

Use this, and do a little research on using the RowDataBound event. If you get stuck, update your question with the code that you've written, and how you're stuck. I'll be happy to help more.

Research is important, and it would be very beneficial for you to build up your skills in that area. It's great to have someone to ask, but there are times when you only have yourself to rely upon.




回答3:


For Boolean, You can do it like this:

<asp:Label ID="Label1" runat="server" Text='<%# Boolean.Parse(Eval("Status").ToString()) ? "Yes" : "No" %>'></asp:Label>  

You can do for other type too.
Hope this will help you.



来源:https://stackoverflow.com/questions/13941184/evaluate-datafield-on-boundfield-to-display-text-accordingly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!