我有一个带有 DataGridView
和 combobox
的表单。 Combobox
通过属性菜单中的 DataSource 填充,我也通过此菜单指定 DisplayMember 和 ValueMember。
我有一个按钮,当我单击它时,另一个表单将显示,我可以将一个新项目添加到我的组合框的数据源中。
当我关闭这个新表单时,我希望我的 comobox 的数据源刷新,以便我可以看到我刚刚添加到组合框中的新项目,但我不知道如何。
我试过:
myComboBox.Refresh();
但什么也没发生
我也试过这个:
myComboBox.Items.Add(myclass.myNewItem);
但它抛出异常:
items collection cannot be modified when the datasource property is set.
请问有人能帮帮我吗?
编辑: 我发现当我在第二种形式中添加一个新项目时,一切都很好,新项目也被添加到数据库中,但是当我返回到第一种形式时,听起来什么都没有发生。所以我将 listBox 添加到第二种形式,回到第一种形式后我没有看到任何添加。我真的不知道为什么 combobox 和 listbox 使用旧数据源,即使我的数据库发生了变化。 然后我尝试了这个并且成功了:
在第二种形式中,我将新项目保存在一个类(名为 transfer)中,当我返回第一种形式时,我这样做了:
DsMy.tblRow row = dsMy.tbl.NewtblRow();
row.BeginEdit();
row.Name = transfer.newName;
row.Id = transfer.newId;
row.EndEdit();
dsMy.tbl.AddtblRow(row);
this.Validate();
tblTableAdapter.Update(dsMy.tbl);
myComboBox.Refresh();
感谢大家的帮助! :)
最佳答案
更新
在包含组合框的主窗体中。我猜你的代码是这样的
private void btnAddNewObjectsButton_Click(object sender, EventArgs e)
{
AddNewObjectsForm form2 = new AddNewObjectsForm();
form2.ShowDialog();
if (form2.isSuccess)
{
this.myComboBox.DataSource = null;
this.myComboBox.Items.Clear();
this.myComboBox.DataSource = db.Object.ToList();//If you work with Entity frame work
cmbCustomer.ValueMember = "Id";
cmbCustomer.DisplayMember = "Name";
}
}
在另一种形式上你的代码将是这样的
public partial class AddNewdbObjects : Form
{
//isSuccess is a flage that will be true if the new object is added to db or no
public isSuccess = false;
//After Constructor in your click event
private void btnSave_Click(object sender, EventArgs e)
{
//Intialize data base source;
_db = new DBEntities();
dbObject obj = new dbObject();
obj.Name = txtName.Text;
try
{
_db.dbObject.Add(cust);
_db.SaveChanges();
isSuccess = true;
this.Close();
}
catch (Exception exc)
{
isSuccess = false;
}
}
}
this solution should work with you.
关于c# - 如何更新 ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51853591/