0

我有包含项目集合的列表框。从列表框中删除项目后,我想从列表框中删除该项目而不重新加载整个集合,这在 winforms 中是否可行?

 private void btnDelete_Click(object sender, EventArgs e)
        {
            MyData sel = (MyData)listBox1.SelectedItem;
            if (...delete data)
            {
                listBox1.Items.Remove(listBox1.SelectedItem);
                MessageBox.Show("succ. deleted!");
            }
            else
            {
                MessageBox.Show("error!");
            }           
        }

我收到错误

设置数据源属性时无法修改项目集合

4

2 回答 2

1

嘿尝试从您的集合中获取选定项目索引,然后按索引删除项目表单集合,然后再次将您的列表框绑定到集合..

我已经制作了示例代码,请参考。

public partial class Form1 : Form
{
    List<String> lstProduct = new List<String>();
    public Form1()
    {

        InitializeComponent();
    }

    public List<String> BindList()
    {

        lstProduct.Add("Name");
        lstProduct.Add("Name1");
        lstProduct.Add("Name2");
        lstProduct.Add("Nam3");
        lstProduct.Add("Name4");

        return lstProduct;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.DataSource = BindList();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // The Remove button was clicked.
        int selectedIndex = listBox1.SelectedIndex;

        try
        {
            // Remove the item in the List.
            lstProduct.RemoveAt(selectedIndex);
        }
        catch
        {
        }

        listBox1.DataSource = null;
        listBox1.DataSource = lstProduct;
    }
}

希望对你有帮助......

于 2013-07-05T12:07:25.480 回答
0

您应该使用 observable 集合作为DataSource. 您可以使用内置的,例如BindingList<T>ObservableCollection<T>

但您也可以考虑创建自己的集合并实现其中一个IBindingListINotifyCollectionChanged接口。

更新

public partial class YourForm : Form
{
    private BindingList<string> m_bindingList = new BindingList<string>();

    private YourForm()
    {
        InitializeComponent();
        yourListBox.DataSource = m_bindingList;

        // Now you can add/remove items to/from m_bindingList
        // and these changes will be reflected in yourListBox.

        // But you shouldn't (and can't) modify yourListBox.Items
        // as long as DataSource is set.
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        // Removing items by indices is preferable because this avoids
        // having to lookup the item by its value.
        m_bindingList.RemoveAt(yourListBox.SelectedIndex);
    }
}
于 2013-07-05T12:40:58.303 回答