0

I have a Listbox I am filling on the back end.
I need to add the (id from db) as the index.
How can I set the index of the Listbox item?

My Code:

 DataTable dt = GetDataTable(sql);

 foreach(DataRow row in dt.Rows)
 {
     lstCategory.Items.Add(row["code"].ToString() + "-" + row["description"].ToString());
 }
Gonen
  • 4,005
  • 1
  • 31
  • 39
user565992
  • 497
  • 2
  • 10
  • 17
  • And your question is? – CalebB Apr 16 '15 at 16:14
  • I am able to add the item but how to add index to that item – user565992 Apr 16 '15 at 16:30
  • You can use the IndexOf() method which will return the index of said item within the items collection. Is that what you're talking about? – CalebB Apr 16 '15 at 16:32
  • No I need to assign an index to each of my item when I add them. Indexof() method returns the index of the item , but I am looking to set an index for the item – user565992 Apr 16 '15 at 17:06
  • 2
    The index is determined by where the item is in the collection. If you are looking to set the position within the collection you'll want to order the list as the answer bellow shows. If you want a separate index value you can set and query try using the tag property. – CalebB Apr 16 '15 at 17:09
  • This is a bad idea. What happens when you delete a row from your database? Your numbering sequence will be missing an ID (deleting item with ID 22 leads to IDs of 20, 21, *23*, 24...), which makes no sense as a collection indexing property. Just sort your items by ID and load them into the collection, then use LINQ or something similar to identify individual items later. Good example of sorting a DataTable/DataView here: http://stackoverflow.com/questions/9107916/sorting-rows-in-a-data-table . – goobering Apr 17 '15 at 08:06

0 Answers0