Hide a Panel when GridView is empty

1.6k views Asked by At

I've a GridView inside a Panel that I want to hide when the child is empty because at the moment remains a fieldset with the legend text and nothing inside.

I've already tried to put something like Panel.Visible = GridView.Rows.Count > 0 in the Page_Load event but it doesn't works well.

How can I obtain the result that I need?

Thank you

Some more details:

If on first load the database table is empty I don't see the fieldset, when I add a row the Panel with the GridView doesn't appears; if on first load I have a row I can see the Panel with the GridView, when I delete the unique row anything disapears but never come back even if I insert a new row. I think that the Page_Load is not the right event.

4

There are 4 answers

1
chenny On BEST ANSWER

In the end I found my problem... I've put the FormView for the insert and the GridView in different UpdatePanels, so unified all in the same UpdatePanel and used this code:

Panel.Visible = GridView.Rows.Count > 0;

in the GridView DataBound event and it worked.

Thank you everyone.

3
Dhrumil On

If you simply want to make your panel visible/invisible based on the Gridview Rows, then its as simple as this :

if(GridView.Rows.Count > 0)
    PanelId.Visible = true;
else
    PanelId.Visible = false;

But make sure you do this code after you have called the Gridview binding function.

Hope this helps.

2
Dhaval On

try this..

Panel.Visible = (GridView.Rows.Count > 0?false:true);

0
ManP On

Please try following steps:

  1. Check for Panel.Visible = GridView.Rows.Count > 0 in a late page event such as Page_PreRender
  2. Add OnRowDeleted event in GridView and check for Panel.Visible = GridView.Rows.Count > 0 if the row deleting is a last row. Also rebind the GridView as GridView.DataBind()
  3. Add OnRowCreated event in GridView and repeat the same process as you did in case of row deletion.

Code:

protected void Page_PreRender(object sender, EventArgs e)
{
    Panel.Visible = GridView.Rows.Count > 0;
}

protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
    GridView.DataBind();
    Panel.Visible = GridView.Rows.Count > 0;

}
protected void GridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
    GridView.DataBind();
    Panel.Visible = GridView.Rows.Count > 0;
}

I hope this will solve your issue.