views:

43

answers:

1

I am creating a WebUserControl in ASP.net and want to be able to access elements of that control later. When I access them though I am trying to access them together. For example, adding a CheckBox and a table to a control and then finding the CheckBox, checking whether it has been ticked and if it has been ticked, get the values from the TextBoxes.

I currently have everything loading on the page from the custom controls, but when iterating through the controls on the page, there doesn't appear to be a control of my WebUserControl type. All of the controls are there on the page, but they exist as seperate ASP.net controls.

Am I thinking about this wrong? Is there a better way to do this?

I'm not sure this is explained very well, please feel free to ask clarifying questions.

+2  A: 

You need to expose the user controls functionality by making public properties or functions to make it do what you need or act like you want. So for example in your case you could have a property in your user control like (you could also do a function):

public List<string> SomeValues
{
    get
    {
        // return null if checkbox is not checked, you could just as easily return an empty list.
        List<string> lst = null;
        if (yourCheckBox.Checked)
        {
            lst = new List<string>();

            // You could have something that iterates and find your controls, remember you  
            // are running this within your user control so you can access all it's controls.
            lst.Add(yourTextBox1.Text);
            lst.Add(yourTextBox2.Text);
            lst.Add(yourTextBox3.Text);
            // etc...
        }
        return lst;
    }
}

Then in your page you can access your user control and call this property to get the values:

// assuming you defined your usercontrol with the 'yourUserControl' ID
List<string> lst = yourUserControl.SomeValues;

The key is to just expose what you want IN your user control so whatever is using it doesn't need to know about it's details or implementation. You should be able to just use it as you would any other control.

Kelsey
This was what I was missing, thank you.
mwright