简体   繁体   中英

Loop through controls inside HTML unordered list in code-behind

I have added controls as following in ul through code behind

HtmlGenericControl ul = new HtmlGenericControl("ul");
  ul.Controls.Add(new LiteralControl("<li>"));
  ul.Controls.Add(new LiteralControl("<img src='" + url + "' alt='" + column.ColumnName.Split('_')[1] + " '/>"));
  ul.Controls.Add(new LiteralControl("<input type='hidden' value='" + column.ColumnName.Split('_')[2] + "' />"));
  ul.Controls.Add(new LiteralControl("</li>"));

Now I want to loop through each control inside ul and find out image tag and hidden field.Please help.I have tried as follow but it is giving error:

foreach (HtmlGenericControl c in ul.Controls)
{
 HtmlGenericControl img = (HtmlGenericControl)ul.FindControl("img");
}

The first problem, which causes an exception is that you are doing a foreach over all Controls in the ul , but you use type HtmlGenericControl for the children while they are just simple LiteralControls . So the foreach tries to cast LiteralControl to HtmlGenericControl and throws exception because it is not possible.

Furthermore, a LiteralControl is, as the name says, just a literal, so it doesn't know it is a img tag. It only knows the full definition <img src='' alt=''/> as its text.

To make your requirement possible, you would have to construct the ul contents using HtmlGenericControls , which you could then query more easily.

HtmlGenericControl ul = new HtmlGenericControl("ul");
var li = new HtmlGenericControl("li");
var img = new HtmlGenericControl("img");
img.Attributes.Add("src", "url");
li.Controls.Add(img);
ul.Controls.Add(li);

Also, to search within this, you will need to go recursively, because the result is a tree of controls:

public HtmlGenericControl FindImg(HtmlGenericControl control)
{            
    foreach (var child in control.Controls.OfType<HtmlGenericControl>())
    {
        if (child.TagName == "img") return child; //found img               

        //not found, recurse into child
        var result = FindImg(child);
        if (result != null) return result;
    }
    return null; //no img found
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM