-2

Normally I would just do:

List<string> list = new List<string>();
    foreach(string element in ul_myLst)
    {
        list.Add(element);
    }

but I'm not really sure how since it doesn't have get enumerator.

Essentially I just want to do some version of storing all the values of an un ordered list into a list in the codebehind. Also sorry if this is a repost, but I only found people inserting items to a list and not saving items from a list.

2 Answers2

1

Would something like this work for you?

html:

<ul runat="server" id="ul_myLst">
 <li runat=server>item1</li>
 <li runat=server>item2</li>
 <li runat=server>item3</li>
</ul>

code behind:

List<string> ListOfStuff = new List<string>();
foreach (Control item in ul_myLst.Controls)
{
   if (item is System.Web.UI.HtmlControls.HtmlGenericControl)
        {
           ListOfStuff.Add(((System.Web.UI.HtmlControls.HtmlGenericControl)item).InnerHtml); 
        }
}
ovaltein
  • 1,185
  • 2
  • 12
  • 34
1

You will need an HTML parser to do this. Dont use a regex to parse HTML.

You could use HtmlAgilityPack.

Markup:

<ul id="ul_myLst" runat="server">
     <li>1</li>
     <li>2</li>
     <li>3</li>
     <li>4</li>
     <li>5</li>
</ul>

Code behind:

HtmlGenericControl ul_myLst = (HtmlGenericControl)this.Page.FindControl("ul_myLst");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(ul_myLst.InnerHtml);

List<string> result = doc.DocumentNode.SelectNodes("li").Select(x => x.InnerText).ToList();

This gives you a list containing:

1 2 3 4 5

Community
  • 1
  • 1
DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • Hey I used NuGet to add HTMLAgilityPack, but it fails on doc.LoadHtml(ul_myLst.InnerHtml); saying object is not an instance of an object. It's seeing HTMLAgilityPack as a namespace do I need to add a reference or something? – StuckOnSimpleThings Jul 12 '13 at 16:04
  • No as it would have failed on the instantiation of the agility pack object. Have you checked that the object `ul_myLst` is not null? – DGibbs Jul 12 '13 at 16:06
  • I can't see a `
      ` anywhere in that markup with an ID or runat server on? You need to add the id like in my example and runat server so that it is accessible to the code behind. Alternatively, you can pass the entire HTML document to the `doc.LoadHtml()` call which will still work.
    – DGibbs Jul 12 '13 at 16:41