我的主窗体上有一个dgv,有一个按钮打开另一个窗体,将一些数据插入到dgv的数据源中。我希望当子窗体关闭dgv自动刷新时。我试图在子窗体关闭事件中添加它,但它不刷新:
private void frmNew_FormClosing(object sender, FormClosingEventArgs e)
{
frmMain frmm = new frmMain();
frmm.itemCategoryBindingSource.EndEdit();
frmm.itemsTableAdapter.Fill(myDatabaseDataSet.Items);
frmm.dataGridView1.Refresh();
}
但是,当我在父窗体上的按钮中添加此代码时,它实际上可以解决问题:
this.itemCategoryBindingSource.EndEdit();
this.itemsTableAdapter.Fill(myDatabaseDataSet.Items);
this.dataGridView1.Refresh();
答案 0 :(得分:38)
有很多方法可以做到这一点,但以下是最简单的方法,它会做你想要的并让你开始。
public partial class Form1 : Form {
public Form1() {
//'add a label and a buttom to form
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
Form2 oForm = new Form2(this);
oForm.Show();
}
public void PerformRefresh() {
this.label1.Text = DateTime.Now.ToLongTimeString();
}
}
public class Form2 : Form {
Form1 _owner;
public Form2(Form1 owner) {
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e) {
_owner.PerformRefresh();
}
}
答案 1 :(得分:0)
您正在创建主窗体的新实例,该实例不会影响实际的主窗体实例。您需要做的是,在主窗体上调用代码,就像您在按钮单击时所说的代码一样:
private void frmNew_FormClosing(object sender, FormClosingEventArgs e)
{
this.itemCategoryBindingSource.EndEdit();
this.itemsTableAdapter.Fill(myDatabaseDataSet.Items);
this.dataGridView1.Refresh();
}
答案 2 :(得分:0)
我们也可以这样做:
我们有form_1和form_2
使用我们的东西的方法是填充我们的form1列表,dataGridView,comboBox或任何我们想要的方法。
Form_1:
public fillComboBox()//Step 1. This is the method with your stuff in Form1
{
foreach(var item in collection myInfo)
{myComboBox.Items.Add(item)}
}
Form_2:
Form1 instanceForm1;//Step 2
public Form2(Form1 theTransporter)//Step 3. This the Form2 contructor.
{
InitializeComponent();
instanceForm1 = theTransporter;//Step 4
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
instanceForm1.fillComboBox();//Step 5 we call the method to execute the task updating the form1
}
我希望它有所帮助...
答案 3 :(得分:0)
那里很棒的答案!另一种方法是:
调用方法刷新gridVieW。
** refreshMethod()
form1
内的datasource
确保您将null
设置为 if (System.Windows.Forms.Application.OpenForms["Form1"]!=null)
{
(System.Windows.Forms.Application.OpenForms["Form1"] as Form1).refreshGridView("");
}
**
colID.setOnEditCommit(event -> {
String newValue = event.getNewValue();
if(checkUniqueness(newValue)){
event.getRowValue().setSID(newValue);
}else {
event.getRowValue().setSID(null);
}
//Weird FX Bug - on the second time through, the value was set, but the table
//column didn't repaint, showing the incorrect amount.
colID.setVisible(false);
colID.setVisible(true);
});
//Stream the backing collection for the table and look for the value that needs to be unique
public boolean checkUniqueness(String value) {
return backingCollection
.stream()
.noneMatch(item -> item.getSID().equals(value));
}