在ListBox winform C#中从单选到多选

时间:2012-06-25 05:57:29

标签: c# listbox

if (productListBox.SelectedIndex >= 0)
                {
                    bool canDelete = true;
                    for (int i = 0; i < bkmNameListBox.Items.Count; i++)
                    {
                        if (((string[])bkmList[i])[1] == _IgnoredBKMID)
                        {
                            canDelete = false;
                        }
                    }
                    if (canDelete)
                    {
                        if (MessageBox.Show("Deleting a product will DELETE ALL debug BKM of this particular product,\r\n Continue?", "Delete Product", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            DatabaseAccess.DeleteProduct(productListBox.SelectedItem.ToString());
                            LoadListBox1();
                            bkmNameListBox.Items.Clear();
                        }
                    }
                    else
                    {
                        MessageBox.Show("You cannot delete this product because one if its Debug BKM is in editing", "Access Denied");
                    }
                }

以上代码删除productListBox中的 ONE 项。如何更改为删除多项?感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

    private void Form1_Load(object sender, EventArgs e)
    {
        bkmNameListBox.SelectionMode = SelectionMode.MultiExtended;
    }
    private void button1_Click(object sender, EventArgs e)
    {

        while (bkmNameListBox.SelectedItems.Count > 0)
        {
            Removedatabasefiled(bkmNameListBox.SelectedItems[0]);
            bkmNameListBox.Items.Remove(bkmNameListBox.SelectedItems[0]);
        }
    }

答案 1 :(得分:0)

listBox1.SelectionMode = SelectionMode.MultiExtended;

循环浏览SelectedIndices并将其逐个删除,因为评论link's表示

for (int i = listBox1.SelectedIndices.Count-1; i >= 0; i--)
    {
     listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);

      //Delete from datasource, in case indices are the same  
      DatabaseAccess.DeleteProduct(listBox1.SelectedIndices[i]);
    }