2013-07-05 144 views
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!"); 
      }   
     } 

我收到提示

项目集合不能当DataSource属性 设置

回答

1

嘿尝试从您的收藏选择项指数则删除项目的形式修改收集索引然后再绑定您的列表框收集..

我已经提出示例代码,请refe河

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; 
    } 
} 

希望它可以帮助你....

+0

需要使用一个ObservableCollection通知删除 – Paparazzi

+1

@Blam的UI按我的知识的ObservableCollection在WPF应用程序不是传统意义上赢形式使用。 –

+0

感谢这篇文章,尝试过,但我在再次加载整个列表时遇到性能问题。 – panjo

0

您应该使用可观察到的集合作为一个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); 
    } 
} 
+0

你能否详细说明这个例子的具体提示。我尝试了@Nerraj Dubey的答案,但是性能非常糟糕。 – panjo

+0

@panjo,我已经更新了我的答案。 –