Reputation: 1256
I have 4 gridviews in my aspx file. I can close their footer like below
if (admin == false){
GridView1.ShowFooter = false;
GridView2.ShowFooter = false;
GridView3.ShowFooter = false;
GridView4.ShowFooter = false; }
But i want to do that using "for" or "for each". Thanks for your helps already now.
Upvotes: 1
Views: 1616
Reputation: 29051
Something like:
void doSomething(Control c)
{
GridView g = c as GridView;
if (g!=null)
{
g.ShowFooter=false;
}
foreach(Control c2 in c.Controls)
{
doSomething(c2);
}
}
Note that I haven't compiled the above. The idea is that you recurse through all of the controls in a certain container (Your page should do nicely), find the GridViews, do something with the gridview (set Showfooter to false, for instance), then recurse through that control's Controls array.
Side note:Someone pointed out that they didn't understand the significance of
GridView g = c as GridView;
Unlike a regular typecase
GridView g = (GridView)c;
the "as" keyword will return null if the cast isn't valid - ie, the control isn't a GridView.
Edit: Another (very readable) way to check the type:
if (c is GridView) g = c as GridView;
Upvotes: 2
Reputation: 9146
Your page has a Controls collection which contains all the top level controls on your page. Under these, each control also has a Controls collection, so a very naive implementation could look like this:
private void FindGridView()
{
foreach (Control ctrl in Page.Controls)
{
GridView gv = ctrl as GridView;
if (gv == null)
{
ParseCollection(ctrl);
}
else
{
gv.ShowFooter = false;
}
}
}
private void ParseCollection(Control parentCtrl)
{
if (gv.Controls == null || gv.Controls.Count == 0)
return;
foreach (Control ctrl in parentCtrl.Controls)
{
GridView gv = ctrl as GridView;
if (gv == null)
{
ParseCollection(ctrl);
}
else
{
gv.ShowFooter = false;
}
}
}
Upvotes: 0
Reputation: 3687
Combine this code with ztech's approach
if (g.GetType() == typeOf(GridView))
{
(GridView)c.ShowFooter = false;
}
This approach should be a little less work intensive as it won't try to cast every control on the page, only the ones whose type is GridView.
Upvotes: 0