Bengi Besceli
Bengi Besceli

Reputation: 3748

How to run a GridView like a Repeater?

Hello I'm using a Gridview and need to change an element's visible property that in all rows while binding.

I tried to change by code-behind but, only the first record's element's property is changed.

The element is a Panel, and the property that I need to change on all records is; Visible property.

How can I run this GridView like a Repeater, to be able to change all Panel elements' Visible property while binding ?

My code is like below :

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
              GridLines="None" DataKeyNames="ID"
              AllowPaging="True" OnDataBinding="GridView1_DataBinding">                    
   <Columns>     
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Panel ID="Panel1" runat="server" Visible="false">
                    <!-- code ... -->
                </asp:Panel>
                <asp:Panel ID="Panel2" runat="server" Visible="false">
                    <!-- code ... -->
                </asp:Panel>
            </ItemTemplate>                            
        </asp:TemplateField>
    </Columns>
</asp:GridView>

CS:

private void Method1(string Key)
{   
    if (Key==1)
    {
        Panel Panel1 = GridView1.Controls[0].Controls[1].FindControl("Panel1") as Panel;
        Panel1.Visible = true;
    }
    else
    {
        Panel Panel2 = GridView1.Controls[0].Controls[1].FindControl("Panel2") as Panel;
        Panel2.Visible = true;
    }
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
    Method1(1);
}

Upvotes: 2

Views: 268

Answers (1)

j.f.
j.f.

Reputation: 3949

Your issue is that you are using the OnDataBinding event. This only occurs once - when the GridView has data bound to it. What you need is the OnRowDataBound event. This will trigger once per row.

OnRowDataBound="GridView1_RowDataBound"

Then handle it in the code behind, finding the panels within each row.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        Panel Panel1 = (Panel)e.Row.FindControl("Panel1");
        //So on and so forth...
    }
}

Upvotes: 1

Related Questions