Reputation: 2911
I need to remove the selected items from a ListBox in asp.net. I keep finding examples for windows forms but not for asp.net.
I have a button click event that copies all items from one listbox to another. I want to be able to select individual items from the second listbox and click a button to remove them.
protected void btnAddAllProjects_Click(object sender, EventArgs e)
{
foreach (ListItem item in lstbxFromUserProjects.Items)
{
lstBoxToUserProjects.Items.Add(item.ToString());
}
}
protected void btnRemoveSelected_Click(object sender, EventArgs e)
{}
Upvotes: 4
Views: 26459
Reputation: 11
Try this to remove selected items from list box.
protected void Remove_Click(object sender, EventArgs e)
{
while (ListBox.GetSelectedIndices().Length > 0)
{
ListBox.Items.Remove(ListBox.SelectedItem);
}
}
Upvotes: 1
Reputation: 1453
Why not simply use the Items.Remove and pass the selected item string value.
ListBox1.Items.Remove(ListBox1.SelectedItem.ToString());
Upvotes: 0
Reputation: 484
I tried some experiments and the technique below works. It's not very efficient, in that it requeries the listbox on each iteration, but it gets the job done.
while (myListBox.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in myListBox.Items where li.Selected == true select li).First();
myListBox.Items.Remove(mySelectedItem);
};
Upvotes: 0
Reputation: 1
protected void ButtonRemoveSelectedItem_Click(object sender, EventArgs e)
{
int position = 0;
for (byte i = 0; i < ListBox2.Items.Count; i++)
{
position = ListBox2.SelectedIndex ;
}
ListBox2.Items.RemoveAt(position);
}
Upvotes: -2
Reputation: 18013
If you just want to clear the selected items then use the code below:
ListBox1.ClearSelection();
//or
foreach (ListItem listItem in ListBox1.Items)
{
listItem.Selected = false;
}
If you mean to what to actually remove the items, then this is the code for you..
List<ListItem> itemsToRemove = new List<ListItem>();
foreach (ListItem listItem in ListBox1.Items)
{
if (listItem.Selected)
itemsToRemove.Add(listItem);
}
foreach (ListItem listItem in itemsToRemove)
{
ListBox1.Items.Remove(listItem);
}
Upvotes: 17