我正在使用Windows窗体应用程序。我已经在要列出的表单上创建了,在“添加”按钮上创建了新窗口。当添加新记录时,数据源正在更新,但是gridview不显示最后添加的记录。为什么会这样?
public MainForm()
{
InitializeComponent();
BindCompanyData();
}
public void BindCompanyData()
{
List<CompanyListModel> companyListModel = new List<CompanyListModel>();
companyListModel = _obiClient.GetCompanies();
companyDataGrid.DataSource = null;
companyDataGrid.DataSource = companyListModel;
companyDataGrid.Refresh();
companyDataGrid.CellClick += new DataGridViewCellEventHandler(DatGridCell_Click);
}
private void btn_addCompany_Click(object sender, EventArgs e)
{
CompanyAddEdit companyAddEdit = new CompanyAddEdit();
companyAddEdit.ShowForm();
}
在按钮上添加它打开新表格。最后,我将该表格称为BindCompanyData()
方法。
private void btn_save_Click(object sender, EventArgs e)
{
string selectedItem = cmbbx_companyType.SelectedItem.ToString();
WriteXML(selectedItem);
this.Close();
MainForm mainForm = new MainForm();
mainForm.BindCompanyData();
}
缺少什么?
答案 0 :(得分:1)
您的问题是您正在使用代码在新创建的表单上运行BindCompanyData();
:
MainForm mainForm = new MainForm();
mainForm.BindCompanyData();
您应该做的是在CompanyAddEdit
参数的MainForm form
构造函数请求中,并传递您在button中使用的当前表单。因此您的代码如下所示:
//Inside CompanyAddEdit form
class CompanyAddEdit : Form
{
MainForm passedForm;
public CompanyAddEdit(MainForm form)
{
this.passedForm = form;
}
//other code
private void btn_save_Click(object sender, EventArgs e)
{
string selectedItem = cmbbx_companyType.SelectedItem.ToString();
WriteXML(selectedItem);
this.Close();
passedForm.BindCompanyData();
}
}
//Inside main form
private void btn_addCompany_Click(object sender, EventArgs e)
{
CompanyAddEdit companyAddEdit = new CompanyAddEdit(this);
companyAddEdit.ShowForm();
}