user8026931
user8026931

Reputation:

ASP.NET Gridview

I formed the table shown below picture 1 with GridView but there is a something which I want and I explain that picture 2 (İ didn't use GridView there).

When the data come from database to column of Durum, if it is Aktif, it shows Aktif Button or if it is Pasif, it shows Pasif Button.

How can do this?

Picture 1

Picture 2

Upvotes: 0

Views: 94

Answers (2)

user1773603
user1773603

Reputation:

Add this TemplateField Code in your GridView:

<asp:TemplateField HeaderText="Durum">
    <ItemTemplate>

        // Bind your durum column from database in Eval
        <asp:Label ID="lblDurum" Visible="false" runat="server" Text='<% #Eval("durum") %>'></asp:Label> 

        <asp:Button ID="btnAktif" Visible="false" runat="server" Text="Aktif" />
        <asp:Button ID="btnPasif" Visible="false" runat="server" Text="Pasif" />

    </ItemTemplate>
</asp:TemplateField>

Code Behind

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button Aktif = e.Row.FindControl("btnAktif") as Button;
            Button Pasif = e.Row.FindControl("btnPasif") as Button;

            string Durum = ((Label)e.Row.FindControl("lblDurum")).Text;
            if (Durum=="Aktif")
                Aktif.Visible = true;
            else
                Pasif.Visible = true;
        }
    }

Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

You can do pretty much whatever you want assuming you don't use default column binding but rather you define your own.

<asp:GridView ... AutoGenerateColumns="false">
   <Columns>
       <asp:TemplateField>
           <ItemTemplate>

               this is where your template can do 
               pretty much anything including conditionals

               <asp:Button runat="server" 
                   ForeColor="<%# Bind("column")=="value" ? "Red" ? "Blue" %> />

Note that dynamic binding can be applied to any property. You could have two different buttons then and dynamically bind their Visible property so that they are visible or hidden depending on a value of one of dataset columns.

More on dynamic templates in multiple tutorials, e.g.

https://msdn.microsoft.com/en-us/library/bb288032.aspx

Upvotes: 0

Related Questions