[英]How to reload form in c# when button submit in another form is click?
我的 C# 中有一個組合框,它位於名為frmMain
的表單中,當我在名為frmSettings
的設置表單中添加(使用按鈕button1_Click
)產品時,它會自動填充。 當我單擊按鈕button1_Click
I want to reload frmMain
時,新添加的產品將可見。
我嘗試使用
frmMain main = new frmMain();
main.Close();
main.Show();
我知道這段代碼很有趣,但它沒有用。 :D
這是windows表格!
編輯
請查看我的程序的這張圖片以便更好地理解。 這是我的frmMain
這是我的設置frmSettings
表單的樣子。 所以,正如您看到的,當我單擊提交按鈕時,我想讓frmMain
重新加載,這樣我添加到設置中的更新值將對frmMain
comboBox 可見。
更新:由於您更改了您的問題,這里是更新您的產品的更新版本
這是您的產品形式:
private frmMain main;
public frmSettings(frmMain mainForm)
{
main = mainForm;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
main.AddProduct(textBox1.Text);
}
它將需要構造函數中的 mainform 將數據傳遞給它。
和主要形式:
private frmSettings settings;
private List<string> products = new List<string>();
public frmMain()
{
InitializeComponent();
//load products from somewhere
}
private void button1_Click(object sender, EventArgs e)
{
if (settings == null)
{
settings = new frmSettings(this);
}
settings.Show();
}
private void UpdateForm()
{
comboBoxProducts.Items.Clear();
comboBoxProducts.Items.AddRange(products.ToArray());
//Other updates
}
public void AddProduct(string product)
{
products.Add(product);
UpdateForm();
}
然后,您可以從表單上的任何地方調用UpdateForm()
,例如另一個按鈕。 此示例僅使用一個局部變量來存儲您的產品。 還缺少添加產品的某些檢查,但我想你明白了......
沒有這樣的內置方法可以根據需要設置所有值。 正如我在評論中提到的,您應該使用所有控件的所需設置創建一個方法,這是示例代碼:
private void ReloadForm()
{
comboBox.ResetText();
dataGridView.Update();
//and how many controls or settings you want, just add them here
}
private void button1_Click(object sender, EventArgs e)
{
ReloadForm(); //and call that method on your button click
}
試試這個代碼。
this.Refresh();
Application.Doevents();
this.Refresh();
Refresh();
this.Hide();
frmScholars ss = new frmScholars();
ss.Show();
this.Close();
frmMain main = new frmMain();
main.Show();
如果您希望從 usercontrol 刷新頁面。這里是我從 usercontrol 刷新表單的示例 查找此重新加載按鈕所在的表單。 然后調用無效選項卡控件並刷新它。
Dim myForm As Form = btnAuthorise.FindForm()
For Each c As Control In myForm.Controls
If c.Name = "tabControlName" Then
DirectCast(c, System.Windows.Forms.TabControl).Invalidate()
DirectCast(c, System.Windows.Forms.TabControl).Refresh() 'force the call to the drawitem event
End If
Next
不需要重新加載整個表單。 只需為表單初始化創建一個函數。 您可以隨時調用此函數。 這將刷新表單。
private void acc_Load(object sender, EventArgs e)
{
form_Load();
}
public void form_Load()
{
// write form initialise codes example listView1.Clear();...
}
private void button1_Click(object sender, EventArgs e) //edit account
{
//Do something then refresh form
form_Load();
}
如果你想在你點擊另一個表單的按鈕時自動更新另一個表單的值,你可以使用定時器控件。 只需將計時器設置為 0.5 秒即可快速更新表單
我認為,通過在單擊按鈕時調用frmMain_load(sender,e)
應該重新加載表單。
您也可以像@Nahum 所說的那樣嘗試Invalidate()
表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.