开发者

Finding controls with specific ID pattern

开发者 https://www.devze.com 2023-04-02 12:25 出处:网络
I have a bunch of <div>\'s in my project named using the syntax block[number]. For example, block1, block2, block3, etc.

I have a bunch of <div>'s in my project named using the syntax block[number]. For example, block1, block2, block3, etc.

I want to iterate through these in the code beh开发者_C百科ind, but I can't get it to work.

Basically what I want to do is to tell the code to look for the control named block[i], where i is a counter I take care of.

I was thinking FindControl but I'm not sure if this will work. Thanks!


you can use something like this in your page:

void IterAllBlocks(Control container, Action<Control> workWithBlock)
{
    foreach(var ctr in container.Controls.Cast<Control>)
    {
       if (ctr.Name.StartsWith("block")
          workWithBlock(ctr);
       if (ctr.Controls.Count > 0) IterAllBlocks(ctr, workWithBlock);
    }
}

using

IterAllBlocks(this, block => { /* do something with controls named "block..." here */ });

PS: for FindControl you need the full identifier - you can try "guessing" them with something like

for(i = 1; true; i++)
{
   var id = string.Format("block{0}"i);
   var ctr = this.FindControl(id);
   if (ctr == null) break;
   // do what you have to with your blocks
}

but I think the LINQ one reads more nicely


Based on CKoenig answer, here is simpler that is working with simple List:

void GetAllBlocks(Control container, List<HtmlGenericControl> blocks)
{
    foreach(var ctr in container.Controls.Cast<Control>)
    {
        if (ctr.Name.StartsWith("block") && ctr is HtmlGenericControl)
            blocks.Add(ctr);
        if (ctr.Controls.Count > 0)
            GetAllBlocks(ctr, blocks);
    }
}

Now to use it have such code: (pnlContainer is the ID of the panel holding all the blocks)

List<HtmlGenericControl> blocks = new List<HtmlGenericControl>();
GetAllBlocks(pnlContainer, blocks);
foreach (HtmlGenericControl block in blocks)
{
    block.InnerHtml = "changed by code behind, id is " + block.Id;
}

When you become more "advanced" use the original code of the answer then have this:

IterAllBlocks(pnlContainer, block => {
    block.InnerHtml = "changed by code behind, id is " + block.Id;
});

Which will do exactly the same thing, just more elegantly.


FindControl will only work if the controls are server controls (i.e., have the attribute runat="server").

You can make mark the div tags with runat="server", and then you can use FindControl on them (be aware it's not recursive, however, so if the controls are nested inside other controls you'll have to do the recursion yourself).

However, the real question is why do you want/need to do this?

0

精彩评论

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