Muhammad Atif Agha
Muhammad Atif Agha

Reputation: 1545

if else on asp.net data grid populating with data source

Hi I have my grid in asp.net C# having data populated from data source, now grid has some columns, there is a column, which has values in 1, 2 or 3 coming from db, i want, if it is 1 then it should display FSL instead of 1, if it is 2 then BTD etc, how can i apply checks from c# or in asp, please help.

Upvotes: 2

Views: 2873

Answers (3)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

Make that a Template column and put in a label:

<asp:TemplateField HeaderText="HeaderText">
  <ItemTemplate>
     <asp:Label ID="lbl" runat="server" ></asp:Label>
  </ItemTemplate>

And then you get it in the RowDataBound event of the Gridview:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRow dr = ((DataRowView)e.Row.DataItem).Row;
        if(dr["ColumnName"].ToString() == "1" )
        {
          ((Label)e.Row.FindControl("lbl")).Text = "FSL";
        }
        else if(dr["ColumnName"].ToString() == "2" )
        {
          ((Label)e.Row.FindControl("lbl")).Text = "BTD";
        }
    }
}

Upvotes: 2

Pankaj Agarwal
Pankaj Agarwal

Reputation: 11309

You can also do using below mentioned ways

<asp:TemplateField HeaderText="HeaderText">
  <ItemTemplate>
     <asp:Label ID="Lbl" runat="server" Text='<%# Convert.ToString(Eval("MyValue"))== "1" ? "FSL" : Convert.ToString(Eval("MyValue")) == "2" ? "BTD" : "Unknown"  %>'></asp:Label>
  </ItemTemplate>
</asp:TemplateField>

Hope it will help for you

Upvotes: 1

FIre Panda
FIre Panda

Reputation: 6637

If you want to get it from query you can do(for sql server)

 SELECT   MyValue = CASE 
             WHEN Col = 1 THEN 'FSL'
              WHEN Col = 2 THEN 'BTD'
             ELSE 'Unknown'
            END
    FROM MyTable 

Upvotes: 1

Related Questions