how to add the selected item from a listbox to list to get the username tha开发者_开发知识库t are selected
my code:
List<String> lstitems = new List<String>();
foreach (string str in lstUserName.SelectedItem.Text)
{
lstitems.Add(str);
}
it show me error saying cannot convert char to string.... how to add the items to list or array
You need to use the SelectedItems
property instead of SelectedItem
:
foreach (string str in lstUserName.SelectedItems)
{
lstitems.Add(str);
}
EDIT: I just noticed this is tagged asp.net - I haven't used webforms much but looking at the documentation it seems this should work:
List<string> listItems = listBox.GetSelectedIndices()
.Select(idx => listBox.Items[idx])
.Cast<string>()
.ToList();
I note that you're using ASP.
For standard C# the following would work:
List<string> stringList = new List<string>();
foreach (string str in listBox1.SelectedItems)
{
stringList.Add(str);
}
If there's only one selected item:
List<String> lstitems = new List<String>();
lstitems.Add(lstUsername.SelectedItem.Value);
Here's a method for getting multiple selections since System.Web.UI.WebControls.ListBox
doesn't support SelectedItems:
// Retrieve the value, since that's usually what's important
var lstitems = lstUsername.GetSelectedIndices()
.Select(i => lstUsername.Items[i].Value)
.ToList();
Or without LINQ (if you're still on 2.0):
List<string> lstitems = new List<string():
foreach(int i in lstUsername.GetSelectedIndices())
{
lstitems.Add(lstUsername[i].Value);
}
You can also do this
List<String> lstitems = new List<String>();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
lstitems.Add(ListBox1.Items[i].Value);
}
If you are using a button to add selected 'item' in string list, just do this.
private void button1_Click(object sender, EventArgs e)
{
List<string> selectedItems = new List<string>();
string item = listBox1.SelectedItem.ToString();
if (!selectedItems.Contains(item))
{
selectedItems.Add(item);
}
}
You can do this in one operation:
IEnumerable<string> groupList = groupsListBox.SelectedItems.Cast<string>();
It will always work for custom objects too:
IEnumerable<CustomObject> groupList = groupListBox.SelectedItems.Cast<CustomObject>();
精彩评论