Form1中:有一个ListBox,一个增加按扭,通过点击增加按扭,打开另一个窗体Form2
Form2中:有一个文本框,一个增加按扭我要实现的效果是:点击Form2中的增加按扭,Form2窗口关闭(这个能实现),刷新Form1窗体中ListBox中的值!请指教,谢谢!
Form2中:有一个文本框,一个增加按扭我要实现的效果是:点击Form2中的增加按扭,Form2窗口关闭(这个能实现),刷新Form1窗体中ListBox中的值!请指教,谢谢!
这些东西MSDN都有!
{
Form2 testDialog = new Form2(); // Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
我倒是想了一个比较笨的方法,不知道正常应该怎么写。
我的想法是:form2设置一个静态的public变量来标记form2是否更新。
当点击点击Form2中的增加按扭,Form2窗口关闭之前,设置这个变量为“已经更新”。
之后在form1的load事件判断form2的这个public变量是否为更新。
若为更新则进行form1中的ListBox重新绑定!达到刷新的目的!
Form2(Form1 p_SetForm)
{
}在Form2里你可以随意修改Form1了
{
Form2 frm2 = new Form2();
frm2.RefreshListboxEvent += new RefreshListboxHandler(frm2_RefreshListboxEvent);
frm2.Show();
} void frm2_RefreshListboxEvent(object sender, EventArgs e)
{
//刷新相应的listbox
MessageBox.Show("OK");
}
form2 private void button1_Click(object sender, EventArgs e)
{
OnRefreshListbox(this,e); this.Close();
} public event RefreshListboxHandler RefreshListboxEvent;
private void OnRefreshListbox(object sender,EventArgs e)
{
if (RefreshListboxEvent != null)
RefreshListboxEvent(this,e);
}
public delegate void RefreshListboxHandler(object sender,EventArgs e);
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this.listBox1);
if (frm.ShowDialog(this) == DialogResult.OK)
{
this.listBox1.Refresh();
}
}
}
}Form2.csnamespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private ListBox lb; public Form2(ListBox vlb)
{
lb = vlb;
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
lb.Items.Add(textBox1.Text);
this.DialogResult = DialogResult.OK;
}
}
}
Form1.cs
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this.listBox1);
if (frm.ShowDialog(this) == DialogResult.OK)
{
this.ListBox.Items.Add(frm.GetContent);//添加调用Form2的属性为项
}
}
}
}
Form2.cs
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private ListBox lb; public string GetContent
{
get
{
return textBox1.text.trim();
}
}
private void button1_Click(object sender, EventArgs e)
{
if(CanAdd())//验证是否为空,空为True,否则为False
{
this.DialogResult = DialogResult.OK;
}
}
}
}