I have a table with several labels lbl1, lbl2...., lbl6... numbe开发者_运维问答red serially
I want to access them in a for loop using a index. Here's my puedocode
//PuedoCode:
int _NUMCOUNT = 6;
string labelname;
string[] strArray = new string[_NUMCOUNT];
//Store some values in strArray
for (int i=0; i<_NUMCOUNT; i++)
{
labelname = "lbl" + (i + 1).ToString();
labelname.Text = strArray[i]
}
Can this be done? I don't want to use a placeholder & add the labels into it. I already have the labels in a formatted table.
Use FindControl Method,
//PuedoCode:
int _NUMCOUNT = 6;
string labelname;
string[] strArray = new string[_NUMCOUNT];
//Store some values in strArray
for (int i=0; i<_NUMCOUNT; i++)
{
Label control=(Label)tab.FindControl("lbl"+i); //Assume that the "tab" is container (table) control.
if(control!=null)
control.Text = strArray[i];
}
Use Control.FindControl Method:
Searches the current naming container for a server control with the specified id parameter.
Label label = FindControl("lbl" + i.ToString()) as Label;
int _NUMCOUNT = 6;
string labelname;
string[] strArray = new string[_NUMCOUNT];
//Store some values in strArray
for (int i = 0; i < _NUMCOUNT; i++)
{
Label lbl = (Label)yourTable.FindControl(String.Format("lbl{1}", i + 1)); //yourTable is the id of table that contains labels
if (lbl != null)
{
lbl.Text = strArray[i];
}
}
You shouldn't need to do that. Just put the labels in a container of some sort (e.g. Panel or Placeholder), and do something like this:
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="Label1" runat="server" />
<asp:Label ID="Label2" runat="server" />
<asp:Label ID="Label3" runat="server" />
</asp:Panel>
And in your code:
foreach (Label label in Panel1.Controls.OfType<Label>())
{
label.Text = "Something";
}
Thanks for the replies. It pointed me in the right direction.
I had to modify the code to
ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1"); //ASP page has master & this is the content page
string lblName = "lbl" + (i + 1).ToString();
Label lblControl = myContent.FindControl(lblName) as Label;
精彩评论