源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#传值方式实现不同程序窗体间通信实例

  • 时间:2021-12-19 07:16 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#传值方式实现不同程序窗体间通信实例
当Form2的AcceptChange按钮按下,需要修改Form1中ListBox中相应列的值,因此可以考虑同时将Form1中的ListBox控件当参数也传入Form2,所有修改工作都在Form2中完成,根据这个思路,Form2代码如下:
[u]复制代码[/u] 代码如下:
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时这么写:
[u]复制代码[/u] 代码如下:
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使用,除非写重载的构造函数,不利于代码的复用
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部