0

Using asp.net webforms I need to store additional data (other than the value field and the text field) in each list item.

Here's my datasource:

class Person 
 {
      public string Name {get;set;}
      public string PersonId {get;set;}
      public string PersonType {get;set;}
 }

 List<Person> lista = GetPersons();

 ListBox1.DataTextField = "Name";
 ListBox1.DataValueField = "PersonId";
 ListBox1.DataSource = lista;
 ListBox1.DataBind();

The DataTextField is the Name. The DataValueField is the PersonId but I also want to bind the PersonType property so that when I retrieve the selected item from the user on the page postback:

       ListItemCollection items = ListBox1.Items;
        foreach (ListItem item in items)
        {
            if (item.Selected == true)
            {
                // Here I want to retrive also
                // the PersonType attribute
                string personType = item.????
            }
        }  

How can I achieve that?

anmarti
  • 5,045
  • 10
  • 55
  • 96
  • Try to cast `item` as a `Person`: `Person p = (Person)item` then you'll be able to get `PersonType` property: `string pt = p.PersonType`. – Maciej Los May 27 '16 at 10:43
  • ListItem does not have built-in support for that, so you have to use attributes collection. And this is not an easy thing to do either, because list items do not store attributes between postbacks. Luckily this was encountered before, see [this thread](http://stackoverflow.com/q/1313447/728795) – Andrei May 27 '16 at 10:47
  • You can concat the strings Name and PersonType using a seperator and then split them up when you want to use them. – Akash Amin May 27 '16 at 10:54

1 Answers1

0

As mentioned in the comments, what you are suggesting is not readily done. ListItem only easily supports value and text.

As a work around, I'd suggest simply retrieving the person by their ID stored in the ListItem:

List<Person> lista = GetPersons();
ListItemCollection items = ListBox1.Items;
foreach (ListItem item in items)
{
  if (item.Selected == true)
  {
    // Here I retrieve the PersonType by matching the ID
    var person = lista.FirstOrDefault( person => person.PersonId == item.value);
    // You may want to check for null...
    string personType = person.PersonType;
  }
}

Alternatively, you may want to make a function for obtaining a Person by PersonId directly, as that seems to be something you may need regularly.

Daniel
  • 12,982
  • 3
  • 36
  • 60