簡體   English   中英

如何將UI從一種形式更新為另一種形式

[英]How to update UI from one form to another form

我有一個Form1,其中包含一個組合框,其中顯示了一些保存在數據庫中的數字,它還包含一個按鈕( butn2 ),該按鈕在單擊時會彈出另一個表單,另一個按鈕( butn1 )從數據庫中更新組合。 在此表單(Form2,某種子表單)上,我嘗試通過創建Form1對象來在單擊按鈕時更新前一個表單(父表單)組合框的數據

但是當我打開並看到組合框時,它仍然顯示相同的數據(未更新)。

是否可以將用戶界面從組合框從一種形式更新為另一種形式? 我的代碼是

Form1代碼:

public Form1()
{
  InitializeComponent(); 
}

Form1.Designer.cs:

Button butn1;
Button butn2;
ComboBox cmb1;
private void InitializeComponent()
 {
  cmb1 = new ComboBox();
  butn1 = new Button();
 }
this.butn1.Click += new System.EventHandler(this.button_Save_Click);
this.butn2.Click += new System.EventHandler(this.button_Save_Click2);

public void button_Save_Click(object sender, System.EventArgs e)
{
  UpdateComboBoxFromMySQL.InsertdataInCombo(this.cmb1 ); //Here i add data in combox through database, the code is correct i verfied it
}
public void button_Save_Click2(object sender, System.EventArgs e)
 {
    Form2 frm2 = new Form2();
    frm2.show();
 }

Form2代碼:

Button butn2 = new Button();
//first i add some data to database, which are added i have seen the table-columns by opening DB. Now i want to update the Combobox from that data
Form1 obj1 = new Form();
this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click); //It calls the function button_Save_Click, i saw on debugging but still it do not update the data.

如何從Form2按鈕單擊更新Form1的此組合框?

讓我們假設您的第一個Form的名稱是Foobar。 在這種情況下,

Form1 obj1 = new Form();
this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click);

這將創建一個新的Form對象,您需要:

Form obj1 = null;
for (int i = ((obj1 == null) && (Application.OpenForms.Count - 1)); i >= 0; i--)
{
    if (Application.OpenForms[i].Name == "Foobar")
        obj1 = Application.OpenForms[i];
}
if (obj1 != null)
{
    this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click);
}

說明: obj1null初始化。 創建一個循環來查找您要查找的Form ,結束符號要么是完成的迭代,要么是找到的Form 如果找到了Form ,則obj1被初始化。 循環之后,如果obj1已初始化,則可以使用它,它的成員和方法,包括但不限於button_Save_Click

您還可以顯示帶有父form1的form2

public void button_Save_Click2(object sender, System.EventArgs e)
 {
    Form2 frm2 = new Form2();
    frm2.Show(this);
 }

然后,您可以通過form2的Owner屬性訪問form1。

this.butn2.Click += new System.EventHandler(Owner.button_Save_Click);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM