user2096512
user2096512

Reputation: 469

Reference a dynamically created control's Text property

I'm trying to refer to a dynamically created label's .Text property but can't find a way. If I try referring to label1.Text it won't let me because it hasn't been created yet.

I'm trying:

Page.FindControl("label" & i.ToString).Text

This doesn't work either, although you can access the control's .ID property that way. Any ideas?

I'm using Visual Studio Express 2012 For Web.

Upvotes: 0

Views: 199

Answers (2)

user2900970
user2900970

Reputation: 761

FindControl returns a System.Web.UI.Control which does not have a .Text property. You need to cast it to a Label. Try this:

Dim label = DirectCast(Page.FindControl("label" & i.ToString()), Label)
label.Text = "foo"

Upvotes: 2

Win
Win

Reputation: 62290

If a control is nested inside other controls, you need to find it recursively. In addition, you want to cast the control to Label control before using Text property.

Here is a helper method. It searches a control recursively.

Helper Method

public static Control FindControlRecursive(Control root, string id)
{
   if (root.ID == id) 
     return root;

   return root.Controls.Cast<Control>()
      .Select(c => FindControlRecursive(c, id))
      .FirstOrDefault(c => c != null);
}

Usage

var myLabel =  FindControlRecursive(Page, "label" + i.ToString) as Label; 
if(myLabel != null)
{
    myLabel.Text = "abc";
}

Upvotes: 0

Related Questions