C# 从 Asp.net ListBox 中删除选定的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9417686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove selected Items from Asp.net ListBox
提问by Ronald McDonald
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.
我需要从 asp.net 的 ListBox 中删除选定的项目。我一直在寻找 windows 窗体的示例,但没有为 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)
{}
采纳答案by WraithNath
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);
}
回答by Manoja
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);
}
回答by bigtech
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);
};
回答by user3040772
int a = txtbuklist.SelectedIndex;
txtbuklist.Items.RemoveAt(a);
回答by BenW
Why not simply use the Items.Remove and pass the selected item string value.
为什么不简单地使用 Items.Remove 并传递选定的项目字符串值。
ListBox1.Items.Remove(ListBox1.SelectedItem.ToString());
回答by Meet Varasada
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);
}
}

