Search code examples
asp.netgridviewboundfield

Evaluate datafield on boundfield to display text accordingly


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.


Solution

  • 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;
        }