手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#传值方式实现不同程序窗体间通信实例
C#传值方式实现不同程序窗体间通信实例
摘要:当Form2的AcceptChange按钮按下,需要修改Form1中ListBox中相应列的值,因此可以考虑同时将Form1中的ListBo...

当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)

{

if (this.listBox1.SelectedItem != null)

{

text = this.listBox1.SelectedItem.ToString();

index = this.listBox1.SelectedIndex;

//构造Form2同时传递参数

Form2 form2 = new Form2(text, listBox1, index);

form2.ShowDialog();

}

}

OK,这样做的好处是直观,需要什么就传什么,缺点也是显而易见的,如果窗体1中需要修改的是一百个控件,难道构造的时候还传100个参数进去?况且如果其他窗体仍然需要弹Form2,那Form2就废了,只能供窗体1使用,除非写重载的构造函数,不利于代码的复用

【C#传值方式实现不同程序窗体间通信实例】相关文章:

C#缩略图多路径多格式保存的实例

C# 得到某一天的起始和截止时间的代码

C# 获取枚举值的简单实例

C#加密解密文件小工具实现代码

C#实现窗体淡入淡出效果的方法总结

c# 生成随机时间的小例子

C#修改MAC地址类的实例

用C#实现启动另一程序的方法实例

C#实现协同过滤算法的实例代码

c# 关闭窗体时提示的小例子

精品推荐
分类导航