开发者

ASP.net -- Identifying a specific control in code behind

I have a page that holds 5 texboxes each name similar but with a numerial suffix. Example:

tbNumber1, tbNumber2, tbNumber3 and so on.

The reason it's like that is because those textboxes are generated dynamically based on some parameter. I ne开发者_如何学运维ver know how many textboxes will be need for a particular record.

How can I loop trough the text contents of these texboxes?

MY first instinct was to do something like the following, but that obviously does't work :)

for (int i = 0; i <= 3; i++)
        {
            string foo = tbNumber+i.Text;
            //Do stuff
        }

Wahts the best way to go trough each of these textboxes?

Thanks!!!


You might be able to do something like this:

for( int i = 0; i < upperLimit; i++ )
{
    TextBox control = Page.FindControl("tbNumber" + i) as TextBox;
    if( control != null ) {
        // do what you need to do here
        string foo = control.Text;
    }
}


Possibly try something like

foreach(Control control in Page.Controls)
{
     //Do stuff
}


If you're generating them dynamically, put them in a List<TextBox> as you generate them:

// in the Page_Load or whereever you generate the textboxes to begin
var boxes = new List<TextBox>();

for (int i = 0; i < numRecords /* number of boxes */; i++) {
  var newBox = new TextBox();
  // set properties here

  boxes.Add(newBox);
  this.Controls.Add(newBox);
}

Now you can loop through the textboxes without using crufty string techniques:

foreach (var box in boxes) {
  string foo = box.Text;
  // stuff
}


What you need is a recursive FindControl like function. Try something like this:

for (int i=0; i<3; i++)
{
    Control ctl = FindControlRecursive(Page.Controls, "tbNumber", i.ToString());
    if (ctl != null)
    {
        if (ctl is TextBox)
        {
            TextBoxControl tbc = (TextBox)ctl;
            // Do Something with the control here
        }
    }
}

private static Control FindControlRecursive(Control Root, string PrefixId, string PostFix)
{
    if (Root.ID.StartsWith(PrefixId) && Root.ID.EndsWith(PostFix))
        return Root;

    foreach (Control Ctl in Root.Controls)
    {
        Control FoundCtl = FindControlRecursive(Ctl, PrefixId, PostFix);
        if (FoundCtl != null)
            return FoundCtl;
    }
    return null;
}


If you're using a CheckBoxList control you should be able to loop through each checkbox in the control.

foreach(var checkbox in checkboxlistcontrol)
{
  string name = checkbox.Text;
}

If you're not using a CheckboxList control, you might want to consider using one as an option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜