Iterate through all items:
foreach(ListItem item in ListBox1.Items)
{
if (item.Selected == True)
{
//item.Value //no to be confused with text
//item.Text //text displayed on UI
}
}
Find specific item text:
private string GetSelectedItem(ListBox container)
{
//string selecteditem = "";
for (int i = 0; i < container.Items.Count; i++)
{
if (container.Items[i].Selected == true)
{
//use .value alternatively if you are trying to get value instead of text
return ListBox1.Items[i].Text; //breaks the loop or
//break; //if you decide to use without a function
}
}
return ""; //error handled in calling func, remove return value if used without a function
//return selecteditem ; //if you want to iterate all items anyway
}
More generalized for re-usability to get text or value, though a little less readable and alot more code:
private static class GetSelectedItem {
private enum ListBox_ContentType {
Text,
Value
}
public string Text(ListBox container) { Get_ContentType(container,ListBox_ContentType.Text);}
public string Value(ListBox container) { Get_ContentType(container,ListBox_ContentType.Value);}
private string Get_ContentType(ListBox container, ListBox_ContentType ContentType) {
for (int i = 0; i < container.Items.Count; i++)
{
if (container.Items[i].Selected == true)
{
if (ContentType == ListBox_ContentType.Value) {
return ListBox1.Items[i].Text;
}
else //ContentType == ListBox_ContentType.Value
{
return ListBox1.Items[i].Value;
}
}
}
return "";
}
}