C#窗体间通讯的几种常用处理方法总结窗体间通讯的几种常用处理方法总结
在进行C#应用程序开发的过程中,经常需要多窗体之间进行数据通信,本文举几个例子,把几种常用的通信方式总结一下,窗
体界面如下图所示:
主窗体Form1是一个ListBox,单击选中某列时,弹出窗体Form2,Form2中两个控件,一个是TextBox,显示选中的该列的文
本,另一个是按钮,点击时将修改后的值回传,且在Form1中修改相应的列的文本,同时Form2关闭。
方法一:传值方法一:传值
最先想到的,Form2构造函数中接收一个string类型参数,即Form1中选中行的文本,将Form2的TextBox控件的Text设置为该
string,即完成了Form1向Form2的传值。当Form2的AcceptChange按钮按下,需要修改Form1中ListBox中相应列的值,因此
可以考虑同时将Form1中的ListBox控件当参数也传入Form2,所有修改工作都在Form2中完成,根据这个思路,Form2代码如
下:
publicpartial class Form2 : Form
{
private string text;
private ListBox lb;
private int index;
//构造函数接收三个参数:选中行文本,ListBox控件,选中行索引
public Form2(string text,ListBox lb,int index)
{
this.text = text;
this.lb = lb;
this.index = index;
InitializeComponent();
this.textBox1.Text = text;
}
private void btnChange_Click(object sender, EventArgs e)
{
string text = this.textBox1.Text;
this.lb.Items.RemoveAt(index);
this.lb.Items.Insert(index, text);
this.Close();
}
}
Form1中new窗体2时这么写:
public partial class Form1 :Form
{
int index = 0;
string text = null;
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgse)