Evaluate datafield on boundfield to display text accordingly

Heinser Diaz picture Heinser Diaz · Dec 18, 2012 · Viewed 8.7k times · Source

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.

Answer

Gregor Primar picture Gregor Primar · Dec 18, 2012

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