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

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)    
        {                
            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#传值方式实现不同程序窗体间通信实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程