Thursday, September 30, 2004

Accessing Properties of User Controls

I've forgotten how to do this enough times now that I'd better write it down. There aren't many posts on the Net explaining this technique, so I'll post it here for my own benefit (if not the benefit of others).

If you want to access the value of a control, say a drop down list or multiple select box, that is embeded within a .NET Web User Control, here's what to do:
  1. build the user conrol (.ascx page) and add the webcontrol -- select box -- you're interested in to the user control;
  2. add two properties -- to get the selectedItem.value, and one to get the selectedItem.text
  3. add the newly created user control to a ASP.NET page;
  4. IMPORTANT: if you keep all your user controls in one directory within your web project, you must add that directory with the dot notation syntax ie: "using project_name.custom_control_directory;"
  5. initialize the user control in the code behind page (aspx.cs) of the page that consumes the user control. This step is not done for you by Visual Studio, the user control must be added manually ie: "protected custom_control_ID custom_control_variable";
  6. the user control properties are now available

1 comment:

Scott Wolff said...

I don't have a VB example (I'm a C# developer), but I think the thing most people get hung up on is this: you have to manually add the control to the code behind. For example. If you have a user control called UserControl1, and you have DropDownList named DropDownList1 inside UserControl1 -- then in the code behind page that you want to add the user control to, you'd have to manually add the reference to the user control, and manually add the DropDownList.

So, in the code behind you'd have something like this:

ProjectName.UsercontrolFolder.Usercontrol UserControl1

System.Web.DropDownList DropDownList1

Then in your cod, to get the SelectedValue property of the UserControl1 e you'd write:

DropDownList1.SelectedValue;

Hope that helps.