Friday, March 16, 2012

Passing a Value to a User Control

I have a user control named uc.ascx and an ASP.NET page named detail.aspx. Both of which are using codebehind, if it makes a difference.

In the aspx page I have the Register directive:

<%@dotnet.itags.org. Register TagPrefix="Employees" TagName="uc" src="http://pics.10026.com/?src=uc.ascx" %>

and
<Employees:uc id="uc" Runat="server" />

In the user control, I have a dropdownlist named "MySelect", and in the codebehind, a string variable named "MySelectValue".

In the aspx page, I have a value that will determine the selected value of MySelect.

Here are some code snippets:

detail.aspx.cs:

private void Page_Load(object sender, System.EventArgs e) {
uc.MySelectValue = "SomeValue";
}

uc.ascx.cs:

public class uc : System.Web.UI.UserControl {
public System.Web.UI.WebControls.DropDownList MySelect;

public string MySelectValue {
get {return MySelect.SelectedValue;}
set {MySelect.SelectedValue = MySelectValue;}
}
}

When I build the solution, I receive a CS0120 error ("An object reference is required for the nonstatic field, method or property 'xxx.Employees.uc.MySelectValue'") on the 'uc.MySelectValue = "SomeValue";' line in detail.aspx.cs.

I've tried everything I can think of, and I am at a total loss. I just can't figure this one out.
Thanks for your help.Are you using the ID as the same name of the user control class name?
I am. Would that confuse the compiler?
it could, I guess :-P, unless you use fully qualified name when declaring & instanciating classes of that type. I would rather don't use the same name however
Thanks, but I'm still getting the same error after renaming the ID.
For anyone having the same issue, a user on the WROX forum, Imar, provided the solution. I neglected to add a declaration for the control in my aspx page.

protected Your.Name.Space.YourControl uc;

However, I still received the same error until I set the ID of the control *back* to "uc".

0 comments:

Post a Comment