当前位置: 移动技术网 > IT编程>开发语言>c# > C#传值方式实现不同程序窗体间通信实例

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

当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使用,除非写重载的构造函数,不利于代码的复用

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网