How to set the value of the GridView bound field based on the condition

2.1k Views Asked by At

I'm looking for a solution to bind a value to a column of a GridView control based on a condition.

Let's say I have a property:

public bool Perm
{
    get;
    set;
}

Based on that property, I want to set the bound field to a particular value.

Here I'm getting a list:

List<MyObject> obj = myservice.GetData().toList();

MyObject has the properties FullBankAcc and HiddenBankAcc.

Based on the value of the Perm property, I want to display either one value or another:

if (Perm)
{
   // bind a column to a HiddenBankAcc
}
else
{
   // bind a column to a FullBankAcc
}

This is the GridView column:

<asp:BoundField DataField="Display the value based on a property" HeaderText="ABA"/>

How can I do something like this?

3

There are 3 best solutions below

1
BloatedCoder On

One way would be add another readonly field to your MyObject class that wraps the logic you want and bind the column to that field.

    public string DisplayValue
    {
        get {
             if (Perm)
             {
               return HiddenBankAcc;
            }
            else
            {
               return FullBankAcc;
            }
       }
   }
4
VDWWD On

If you switch to a TemplateField you can do it inline.

<asp:TemplateField HeaderText="BankAcc">
    <ItemTemplate>
        <%# string.IsNullOrEmpty(Eval("HiddenBankAcc").ToString()) ? Eval("FullBankAcc") : Eval("HiddenBankAcc")%>
    </ItemTemplate>
</asp:TemplateField>

Or as Boolean

<asp:TemplateField HeaderText="BankAcc">
    <ItemTemplate>
        <%# Convert.ToBoolean(Eval("FullBankAcc")) ? Eval("FullBankAcc") : Eval("HiddenBankAcc")%>
    </ItemTemplate>
</asp:TemplateField>
0
Anh-Tuan N. On

1.) Create the function in your page's code behind

   public string DisplayValue(Perm)
   {
             if (Perm)
             {
               return HiddenBankAcc;
            }
            else
            {
               return FullBankAcc;
            }
   }

2.) Assuming the value of variable "Perm" is in your gridview's datasource, on the aspx page

<asp:BoundField HeaderText="ABA">
   <asp:Label runat="server" Text='<%# DisplayValue((bool)Eval("Perm"))%>' </asp:Label>
</asp:BoundField>