Setting UserControls properties in .ascx file

D

DC

Hi,

I want to keep all my layout information in the .ascx file of a
UserControl. If I require layout related data in codebehind, I would
usually use properties defined in the codebehind, e.g.

string tdStyle;

public string TdStyle
{
get { return tdStyle; }
set { tdStyle = value; }
}

and then set the property in the .ascx, like so:

<script type="text/C#" runat="server">
protected override void OnInit(EventArgs e)
{
TdStyle = "background-color:red;";
}
</script>

This also has the advantage that I could set the property TdStyle in
the .aspx file hosting the .ascx, too.

However, I dislike overriding OnInit in the .ascx (ideally I want to
keep as much code out from that file as possible) just to set some
properties. An alternative approach is using literals like

<asp:Literal ID="TdStyle" runat="server"
Visible="false">background-color:red;</asp:Literal>

but here I need to define a control for every property and the property
data is always a string. Too much overhead.

I was wandering, if someone knows a more elegant approach.

Regards
DC
 
M

Mark Fitzpatrick

Why do you need to set it in the OnInit? Your tdStyle string is
uninitialized and shoule be initialized anyways to avoid issues. Why not set
it there

string tdStyle = "background-color:red";

One of the first things they teach in programming, always initialized your
variables so you can guarantee that they are actually a value. What value
does an integer x have when it's definited as int x; It's up to the
runtime and/or system to determine it. In this case it should always be int
x = 0; or some other number to start to guarantee that the variable is
initialized.
 
D

DC

Hi Mark,

I can do this:

string tdStyle = "background-color:red";

only in codebehind, and you are right in that it actually makes sense
to provide a default value for the property.

However, I want to make sure that all my layout information can be
configured in the .ascx, so I need a way to set the property in the
..ascx file. And the only way I found so far is overriding OnInit - and
I don't really want to do that in the .ascx file.

Regards
DC
 

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,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top