我有包含项目集合的列表框。从列表框中删除项目后,我想从列表框中删除该项目而不重新加载整个集合,这是否可以在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!");
}
}
我收到错误
数据源属性时,无法修改项集合 设置
答案 0 :(得分: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;
}
}
希望它可以帮助你......
答案 1 :(得分:0)
您应该将可观察集合用作DataSource
。
您可以使用内置版本,例如BindingList<T>
和ObservableCollection<T>
。
但您也可以考虑创建自己的集合并实施IBindingList
或INotifyCollectionChanged
界面。
<强>更新强>
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);
}
}