jeetz
jeetz

Reputation: 1

Use a variable to reference a web server control in C#

In C#, I want to assign all 10 Checklistboxes on my page with a value (e.g. 1). What is the syntax so that I can use a variable? I.e. checklistbox(i).selectedIndex = 1;

for (int i = 1; i < 11; i++)
{
  checklistbox1.selectedIndex = 1;
  checklistbox2.selectedIndex = 1;
  checklistbox3.selectedIndex = 1;
  ...
  checklistbox10.selectedIndex = 1;
}

Upvotes: 0

Views: 651

Answers (3)

Adam Lear
Adam Lear

Reputation: 38768

You can loop over all the controls on the page and pick out the ones you need as described in this blog post by Kris Steele:

foreach (Control masterControl in Page.Controls)
{
    if (masterControl is MasterPage)
    {
        foreach (Control formControl in masterControl.Controls)
        {
            if (formControl is System.Web.UI.HtmlControls.HtmlForm)
            {
                foreach (Control contentControl in formControl.Controls)
                {
                    if (contentControl is ContentPlaceHolder)
                    {
                        foreach (Control childControl in contentControl.Controls)
                        {
                            if(childControl is CheckBoxList)
                            {
                                ((CheckBoxList)childControl).SelectedIndex = 1;
                            }
                        }
                    }
                }
            }
        }
    }
}

This may not be a good idea if you have a lot of controls on the page.

Upvotes: 1

Praveen
Praveen

Reputation: 1449

I guess you should use "FindControl" method inorder to do that as shown below.

 for (int i = 1; i <= 10; i++)
 {
      (Page.FindControl("checklistbox" + i) as CheckBox).SelectedIndex = 1;
 }

"checklistbox" is assumed as "ID" that is prefixed for all the checkboxes.

Hope this helps!!

Upvotes: 2

SLaks
SLaks

Reputation: 887275

You should create a List<CheckBoxList>:

var cbs = new List<CheckBoxList> { thingy, otherThingy, ... };

foreach (var cb in cbs)
     cb.SelectedIndex = 0;

Upvotes: 0

Related Questions