Reputation: 4104
I'm updating some old code that loops over a collection and sets some UI display properties based on the values in the object.
Unfortunately, it's hardcoded like so:
for (int i = 0 ; i < length; i++) // length is going to be 30+
{
// do some stuff
switch (i)
{
case 1:
lbl1.Text = myVariable;
break;
case 2:
lbl2.Text = myVariable;
break;
....
case 15:
lbl15.Text = myVariable;
break;
}
}
(I say unfortunately because it actually has 5 more lines per case that I left out, which do the exact same thing regardless of the case)
Now, I could put all 15 label
controls in an array and in my for
loop just do if (i <= 15) lblArr[i].Text = myVariable;
but I'd prefer not to have to hardcode this array. If we add more labels then we'll need to remember to update this function.
So, I'm trying to find a way to find all the controls within a particular HTML element, but I cannot find a working example in a .NET language.
In winforms I could simply just iterate over someControl.Controls
and find the appropriate ones, but since these are labels in an HTML table and not a repeater or anything like that I don't know how to find them. Any ideas?
Upvotes: 1
Views: 1382
Reputation: 1643
Depending on the complexity of the code, it may be cleaner to just retrieve a db row on page load, set it to a property on the codebehind (or put its data in an object that is a property on the page), and then bind to it using code blocks. You can get rid of all of the <asp:Label>
elements that way too.
e.g.
<table>
<tr>
<td><span><%: myObject.Property1 %></span></td>
</tr>
</table>
That way you can make all of your binding declarative and remove the need for procedural codebehind logic to loop through and set things.
Upvotes: 0
Reputation: 490
How about jquery? It's definteily much faster than .NET. give it a shot... :)
$(function () {
var myTableId = "yourTableId";
var yourReplacementText = "yourReplacementText";
var allSpansUnderYourTable = $('#' + myTableId).find('span');
$.each(allSpan, function (index, item) {
item.innerHTML = yourReplacementText;
});
});
Upvotes: 0
Reputation: 148524
You can use the FindControl method :
for (int i = 0 ; i < length; i++)
{
Label ans = FindControl(string.Format("lbl{0}",i)) as Label ;
if (ans!=null) and.Text = myVariable
}
Upvotes: 1