FilllanTroop
FilllanTroop

Reputation: 87

iterate through ASP:Buttons

I am kind of newbie and I have an issue with ASP:Button controls.

There is about 60 buttons on the page, typical XAML looks like this:

<asp:Button class="tile" ID="Button1" runat="server" Text="Domains"/>

I need to iterate through all of the buttons on the page to change properties and I don't want to do it one by one.

I've found many suggestions here and there, but nothing works. My code behind is:

for (int i = 1; i < 59; i++)
{ 
    String butt = String.Format("Button{0}", i);
    var btn = FindControl(butt);
    btn.Visible = false;
}

Error is that there is no object reference. btn is null. I tried to inspect element in running application and it says ID of element is "MainContent_Button1" - tried that too, does not work. Other thing I tried is

foreach(var button in this.Controls.OfType<Button>())
{
    button.Visible = false;
}

I came to conclusion that asp:button is a) not a control of button type b) its ID is somehow generated when the application is run and therefore there is no control with id Button1 to be found.

Can anyone please explain that to me? I'd really like to understand why is it behaving like that and what exactly is the purpose of this behavior.

Thanks

Edit: I even tried to remove the loop completely and modify one specific button using FindControl method. Does not work either.

 var btn = FindControl("Button1");
 btn.Visible = false;

result: System.NullReferenceException: 'Object reference not set to an instance of an object.'

Upvotes: 1

Views: 335

Answers (1)

VDWWD
VDWWD

Reputation: 35514

It looks like you are using a Master Page. Using FindControl on a Master Page works slightly different than on a normal page.You first need to find the correct ContentPlaceHolder in which the Buttons are located and use FindControl on that ContentPlaceHolder.

ContentPlaceHolder cph = Master.FindControl("MainContent") as ContentPlaceHolder;

for (int i = 1; i < 9; i++)
{
    String butt = String.Format("Button{0}", i);
    var btn = cph.FindControl(butt);
    btn.Visible = false;
}

Upvotes: 3

Related Questions