Accessing the instances of the web user control

  • Thread starter Thread starter Vivek Sharma
  • Start date Start date
V

Vivek Sharma

Hi,

I have created a dropdownlist as a web user control. I am using its
multiple instances on the webpage. How do I access the selectedValue of
each instance? All the instances have different IDs.

Thanks

Vivek
 
Hi Vivek,

The proper way to access control members is through a public interface that
encapsulates access. Add a property to your User Control that delegates to
the DropDownList, something like this:

public string SelectedValue
{
get
{
return DropDownList1.SelectedValue;
}
set
{
DropDownList1.SelectedValue = value;
}
}

Then on your Web Form, add a reference to each control, naming the variable
the same as the id you used for each user control on the page, something
like this:

protected WebUserControl1 WebUserControl11;


WebUserControl is the name of the User Control type you created.
WebUserControl11 is the id of a control of type WebUserControl1 on the Web
Form.

You can then access the DropDownList control on the user control through the
public property, via your Web Form, something like this:

string selectedVal = WebUserControl11.SelectedValue;

Joe
 
Thanks Joe,

I am not sure where am I failing ...

This is what I tried

My web user control filename: uctlRating.ascx contains dropdownlist
As mentioned I created a public interface.

I declared the contol at the top of the HTML
<%@ Register TagPrefix="ucRating" TagName="Rating" src="...">

In HTML I am accessing the instances of the web control

<ucRating:Rating id="Rating1" runat="server"></ucRating:Rating>
<ucRating:Rating id="Rating2" runat="server"></ucRating:Rating>

---------------------------------------------------------------------------------------------

My aspx.cs looks like this

protected System.Web.UI.WebControls.DropDownList Rating1

and later I am accessing

string s = Rating1.SelectedValue.ToString();
 
The message is correct because your control type is not DropDownList - its
type is Rating. If you examine the code-behind for the user control, you'll
find that its type is defined as:

public class Rating: System.Web.UI.UserControl
{
....
}

which means that it should be defined as a field in the class of the
code-behind of your Web Form like this:

protected <your namespace>.Rating Rating1

where <your namespace> should be replaced with the namespace that the User
Control code-behind class, Rating, is defined in to fully qualify the
declaration.

Then use the property access technique I showed you to encapsulate access to
the DropDownList control.

Joe
 
Back
Top