views:

80

answers:

5

Hello,

I have multiple literals on a page. For example,

<asp:Literal id="Label1" runat="server" />

I have around 10 of these on one page and want to fill them all with the same value. Is there a good way to do that without referencing the id for each control?

A: 

The only way I've seen it done is make the id's a loopable name (e.g. Label1 - Label10) and loop through referencing the id. But we didn't try too hard for a different solution!

dsrekab
+2  A: 

Create a public property that holds the value you want to display and in the aspx use

<%= propertyName %>

everywhere you want to display the value.

Jimmie R. Houts
A: 

If you're using resource files, you can set the meta:resourcekey attribute to the same value for all 10 of them.

Greg
A: 

Are the Literals located in a single Container (for instance, a Panel) or are they littered about the page? If they are in a single container which does not contain too many other non-relevant controls, it would be as simple as looping through the Container's Controls collection.

Yes, I'm well aware that a Page is a Container as well, but it is almost always very inefficient to loop through all the controls in a Page. I wouldn't recommend it at all.

Cerebrus
A: 

How are your labels named. If they have a common naming convention like Label1 - Label10 then you could do

for(int i = 1; i <= 10; i++)
{
    Literal l = Page.FindControl(string.Format("Label{0}", i)) as Literal
    if(l != null)
        l.Text = "Whatever";
}

If they're not named similarly, you could just stick the label names in an array and loop through that instead of having 10 explicit .Text = statements. e.g.

string [] litNames = new string [] { "litFirst", "otherLit", "someOtherVar" }

foreach(string s in litNames)
{
    Literal l = Page.FindControl(s) as Literal
    if(l != null)
        l.Text = "Whatever";
}
Eoin Campbell