我有以下代码来填充DataGridViewComboBoxColumn
try
{
itemReader = sc.ExecuteReader();
itemDT = new DataTable();
itemDT.Columns.Add("id", typeof(string));
itemDT.Columns.Add("ar_desc", typeof(string));
itemDT.Load(itemReader);
itemIDcmbColmn.ValueMember = "id";
itemIDcmbColmn.DisplayMember = "ar_desc";
itemIDcmbColmn.DataSource = itemDT;
}
catch (Exception e)
{
MessageBox.Show("Exception - populateGridComboBox(): " + e.Message);
}
finally
它填充了组合框。我有一个按钮,可以在DataGridViewComboBoxColumn中插入新记录,打开另一个FormB形式,并提示用户输入新项目的名称和ID。但问题是,在我关闭并重新打开FormA之前,新添加的项目不会出现在comboBox中。这是我在FormB中的代码:
BindingSource bs = new BindingSource();
DataGridViewComboBoxColumn itemCmbClmn = prcFrm.itemIDcmbColmn; //Get FormsA DataGridViewComboBoxColumn
DataTable itemDataTable = prcFrm.ItemData; //Get FormA datatable
itemCmbClmn.ValueMember = itemID.ToString();
itemCmbClmn.DisplayMember = txtItemAr.Text;
bs.DataSource = itemDataTable;
itemCmbClmn.DataSource = bs;
prcFrm.dataGridView1.Update();
当我运行addNew时,我得到了一个不存在Field的异常。请帮助,我是C#和visual studio的新手,提前谢谢
答案 0 :(得分:0)
在FormB中:
public event ItemAdded ItemAddedNotify;
#region OwnEventsAndDelegates
public delegate void ItemAdded(object sender, ItemAddedEventArgs e);
public class ItemAddedEventArgs : EventArgs
{
string _valueMember;
public string ValueMember
{
get { return _ValueMember; }
set { _ValueMember = value; }
}
string _displaymember;
public string DisplayMember
{
get { return _displayMember; }
set { _displayMember = value; }
}
public ItemAddedEventArgs(string pValueMember, string pDisplaymember)
{
_valueMember = pValueMember;
_displayMember = pDisplaymember;
}
}
#endregion
稍后,在FormB中,您现在执行update(),您只需引发事件,而不是更新:
ItemAddedNotify(this,new ItemAddedEventArgs(itemID.ToString(), txtItemAr.Text));
BUT。但是当您打开formB时,您必须订阅该事件。 在Mainform中,在实例化formB之后,但在显示之前,你应该这样做:
this.formB.ItemAddedNotify += new FormB.ItemAddedNotify(On_ItemAdded);
方法
On_ItemAdded(object sender, FormB.ItemAddedEventArgs e)
{
// Here You will have to add the stuff.
// IT MIGHT BE BETTER TO USE TYPED DATASETS/TABLES.
// It also might be, that the record will be visible ONLY after
// closing formB. Please let me know.
}
您的MainForm中也必须存在。
在关闭formB之后,不要忘记取消订阅该事件,相当于+ =,但使用 - =。