[英]Delete selected items from listbox
我想這樣做,但是列表框在每次刪除時都會更改,因此即使我嘗試創建一個新對象,它也會引發運行時異常。
我試過這樣:
ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
selectedItems = lstClientes.SelectedItems;
if (lstClientes.SelectedIndex != -1)
{
foreach (string s in selectedItems)
lstClientes.Items.Remove(s);
}
else
MessageBox.Show("Debe seleccionar un email");
在迭代(使用foreach
)時不能修改集合。 而是使用反向for
循環:
ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
selectedItems = lstClientes.SelectedItems;
if (lstClientes.SelectedIndex != -1)
{
for (int i = selectedItems.Count - 1; i >= 0; i--)
lstClientes.Items.Remove(selectedItems[i]);
}
else
MessageBox.Show("Debe seleccionar un email");
使用反向循環可確保您在刪除它們后不會跳過任何內容。
selectedItems = lstClientes.SelectedItems;
此行不會創建新集合,而是設置對列表框中的集合的引用。 因此,您正在遍歷一個集合並嘗試立即從中刪除項目。 這不可能
您可以使用它,例如:
foreach (string s in lstClientes.SelectedItems.OfType<string>().ToList())
lstClientes.Items.Remove(s);
就像這樣簡單:
while (lst.SelectedItems.Count > 0)
{
lst.Items.Remove(lst.SelectedItems[0]);
}
lst.Items.Remove(lst.Items[lst.SelectedIndex]);
如果您不想循環,可以使用它
注意:這僅適用於刪除 1 個項目(多選它只會刪除第一個選定的項目)
為了建立帕特里克的回答,我傾向於使用反向索引刪除,因為它保留了待刪除項目的索引,而它們被刪除而不刪除相同的項目。
private void BtnDelete_Click(object sender, EventArgs e) {
if (listBox.SelectedIndex == -1) {
return;
}
// Remove each item in reverse order to maintain integrity
var selectedIndices = new List<int>(listBox.SelectedIndices.Cast<int>());
selectedIndices.Reverse();
selectedIndices.ForEach(index => listBox.Items.RemoveAt(index));
}
我找到了更好的解決方案。
if (listBoxIn.SelectedItems.Count != 0)
{
while (listBoxIn.SelectedIndex!=-1)
{
listBoxIn.Items.RemoveAt(listBoxIn.SelectedIndex);
}
}
我今天遇到了同樣的問題,想要一些更清潔的東西,並提出了這個 Linq 解決方案:
foreach (int index in myListBox.SelectedIndices.Cast<int>().Select(x => x).Reverse())
myListBox.Items.RemoveAt(index);
與 Patrick 的向后迭代和刪除選定項目的解決方案基本相同。 然而,我們不是向后迭代,而是反轉要刪除的項目列表並向前迭代。 我們不再遍歷原始枚舉,因此我們可以刪除 foreach 中的項目。
這是刪除所選項目的最簡單方法
for(int v=0; v<listBox1.SelectedItems.Count; v++) {
listBox1.Items.Remove(listBox1.SelectedItems[v]);
}
這適用於 WPF 中的多個和單個選擇。
while (xListBox.SelectedItems.Count > 0)
{
xListBox.Items.RemoveAt(SavedItemsListBox.SelectedIndex);
}
創建一個全局變量:
public partial class Form1 : Form
{
Int32 index;
}
然后在選定的索引更改處將該索引保存在您定義的 var 中:
private void lsbx_layers_SelectedIndexChanged(object sender, EventArgs e)
{
layerindex = lsbx_layers.SelectedIndices[0];//selected index that has fired the event
}
最后,刪除元素:
lsbx_layers.Items.RemoveAt(Layerindex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.