C# 如何刷新列表框的数据源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17615069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh DataSource of a ListBox
提问by panjo
Form has one Combobox and one ListBox. When the "Add" button is clicked, I want to add the selected item from the ComboBox to the ListBox.
表单有一个组合框和一个列表框。单击“添加”按钮时,我想将组合框中的所选项目添加到列表框。
public partial class MyForm:Form
{
List<MyData> data = new List<MyData>();
private void ShowData()
{
listBox1.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
ShowData();
}
}
With this example, the selected item is replaced with the new selection inside ListBox. I need to add the item to the list.
在此示例中,所选项目将替换为 ListBox 中的新选择。我需要将该项目添加到列表中。
What is wrong with my code?
我的代码有什么问题?
采纳答案by dwonisch
listbox1.DataSourceproperty looks for value changes but by assigning the same list all the time the value won't really change.
listbox1.DataSource属性查找值更改,但通过始终分配相同的列表,值不会真正更改。
You can use a BindingList<T>, instead of your List<T>, to automatically recognize new items added. Your ShowData() method must be called once at startup.
您可以使用BindingList<T>代替List<T>来自动识别添加的新项目。您的 ShowData() 方法必须在启动时调用一次。
public partial class MyForm:Form
{
public MyForm(){
InitializeComponent();
ShowData();
}
BindingList<MyData> data = new BindingList<MyData>();
private void ShowData()
{
listBox1.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
}
}
回答by gzaxx
I would suggest to use BindingSourceas it would properly update connected controls.
我建议使用BindingSource它,因为它会正确更新连接的控件。
public partial class MyForm : Form
{
List<MyData> data = new List<MyData>();
BindingSource bs = new BindingSource();
public MyForm()
{
IntializeComponents();
bs.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
listBox1.DataSource = bs;
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
bs.ResetBindings(false);
}
}
Changing controls data source on fly produces strange result sometime.
更改控件数据源有时会产生奇怪的结果。
回答by rajeemcariazo
The listbox didn't detect that you have changed the DataSource. It will only refresh when Datasourcehas changed, so set DataSourceto null first:
列表框未检测到您已更改DataSource. 它只会在Datasource发生更改时刷新,因此DataSource请先设置为 null:
listBox1.DataSource = null;
listBox1.DataSource = data;
You could also clear the items then set the DataSource again:
您还可以清除项目然后再次设置数据源:
listBox1.Items.Clear();
listBox1.DataSource = data;
回答by jduncanator
Alternatively and probably the most correct way to implement this is to use the provided ObservableCollection<T>. It is designed with the sole purpose of implementing INotifyCollectionChanged.
或者,可能最正确的实现方法是使用提供的ObservableCollection<T>. 它设计的唯一目的是实现INotifyCollectionChanged.
public partial class MyForm : Form
{
ObservableCollection<MyData> data = new ObservableCollection<MyData>();
public MyForm()
{
listBox1.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
}
}
Because ObservableCollection<T>implements INotifyCollectionChangedthe DataSource binding will automatically update the ListBox whenever your data changes.
因为ObservableCollection<T>实现INotifyCollectionChangedDataSource 绑定将在您的数据更改时自动更新 ListBox。
回答by Frank Odoom
Call ShowData()when the form initializes to populate your listbox on initialization
ShowData()在表单初始化时调用以在初始化时填充您的列表框
public Department()
{
InitializeComponent();
ShowData();
}
ShowData()Method, where BindingSource, DisplayMemberand ValueMemberare set
ShowData()方法,其中BindingSource,DisplayMember与ValueMember设置
private void ShowData()
{
using (var uow = new UnitOfWork(new SellContext()))
{
listBox1.DataSource = uow.Departments.GetAll().ToList();
listBox1.DisplayMember = "DepartmentName";
listBox1.ValueMember = "DepartmentId";
//listBox1.Invalidate();
}
}
In the implementation below when a department is deleted from database the listbox refreshes with the current collection
在下面的实现中,当一个部门从数据库中删除时,列表框会刷新当前集合
private void button1_Click(object sender, EventArgs e)
{
try {
using (var uow = new UnitOfWork(new SellContext()))
{
int count = uow.Departments.FindDepartmentByName(txtDeptName.Text.ToString());
if (count>0)
{
MessageBox.Show("This Department Already Exists", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
else
{
department dept = new department();
dept.DepartmentName = txtDeptName.Text.ToString();
uow.Departments.Create(dept);
if (uow.Complete() > 0)
{
MessageBox.Show("New Department Created", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtDeptName.Text = "";
ShowData();
}
else
{
MessageBox.Show("Unable to add Department", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtDeptName.Text = "";
ShowData();
}
}
}
}
catch(Exception ex)
{
ex.ToString();
}
}
回答by Federico De Luca
Maybe this solution has not the better performance, but after many tries and a few hours it was what it worked for me:
也许这个解决方案没有更好的性能,但经过多次尝试和几个小时后,它对我有用:
This line was executed on the form constructor:
这一行是在表单构造函数上执行的:
listBox1.DataSource = myData;
This lines were executed after the information was modified:
listBox1.DataSource = new List<Movil>();
listBox1.DataSource = myData;
Hope it helps!
希望能帮助到你!

