How to set property of control?

B

brett

I have an aspx page with a user control (uc1) on it. There is a DIV
tag in the user control and I'd like to set its width. In uc1, I have
a private string varible with a value of "100px". In the DIV I do
this:

<div class="box" style="width: <%= uc1.boxWidth %>;">

However, when the aspx page loads, I immediately get an error that uc1
doesn't exists. It occurs before the aspx constructor or PreInit()
occur. How can I get the above variable to render client side?

I did try something different. After adding runat=server and giving
it an Id, if I try to assign it in the code behind, it isn't
recognized because the control isn't created anywhere. I could drop
in an ASP panel there and probably make it do what the DIV does. I'll
also have code behind access. But how do you take an HTML element,
give it a runat=server and then be able to reference it in the code
behind? That control has to be created somewhere for the code behind
reference.

Here's what it looks like after the above modifications:

<div runat="server" id="mainbox" class="box" style="width: 125px">

If there is a generally better way to do it, please suggest.

Thanks,
Brett
 
G

Guest

Brett,

The best way to deal with in such case is to make internal di div runat
server (or use asp:panel control) and expose a property from user control:

-- begin user control aspx code --
<div runat="server" id="mainBox">
<!--a HTML/ASP.NET content/controls go here-->
</div>
-- end user control aspx code --

-- begin user control code behind --
....
public string MainBoxWidth
{
get
{
return mainBox.Width;
}
set
{
mainBox.Width = value;
}
}
....
-- end user control code behind --

Now you may use the property both declaratively (aspx code):

<uc1:MyUserControl MainBoxWidth="100px" runat="server"
ID="myUserControl"></uc1:MyUSerControl>

and programatically (code behind):

myUserControl.MainBoxWidth = "100px";

That's the actuall design pattern.
Hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top