【问题标题】:Passing Values from One Form to an Other Form as Consutrutor Parameters将值从一个表单传递到另一个表单作为构造函数参数
【发布时间】:2014-02-07 07:07:52
【问题描述】:

有form1和form2两种形式。 form12 按钮点击需要在 form2 上传递一些值作为 form2,s 构造器参数,并且在 form1 的按钮点击时 form2 需要显示和使用这些值。

//form1
{
    private void btn_Click(object sender, EventArgs e)
    {
     int a=1;
     int b=2;
     int c=3;
    }
}
//form2
{
 private int a=b=c=0; 
 public Frm2(/*pass parameters here*/)
        {
            InitializeComponent();
        } 
}

【问题讨论】:

  • 您可以编写自定义构造函数,例如 public Frm2(/*pass parameters here*/) : this(){/*you code for params*/}

标签: c# winforms


【解决方案1】:

使用你的问题代码我试图解决我们的问题:)

//form1

 {
        private void btn_Click(object sender, EventArgs e)
        {
         int a=1;
         int b=2;
         int c=3;

         Form2 frm=new Form2(a,b,c);
         frm.show();
        }
    }
//form2


 {
     private int a=b=c=0; 

     //it will be main load of your form 
     public Frm2()
            {
                InitializeComponent();

            } 

     //pass values to constructor 
     public Frm2(int a, int b, int c)
            {
                InitializeComponent();
                this.a = a;
                this.b = b;
                this.c = c;
            } 
    }

【讨论】:

    【解决方案2】:

    简单的解决方案是在 Form2 上创建一个方法来初始化你需要的任何东西。

    例如:

    public class Form2
    {
    
      public Form2()
      {
         InitializeComponent();
      }
    
      // Call this method to initialize your form
      public void LoadForm(int a, int b, int c)
      {
          // Set your variables here
      }
    
      // You can also have overloads to cater for different callers.
      public void LoadForm(string d)
      {
          // Set your variables here
      }
    
    }
    

    所以您现在需要在按钮的Click 事件处理程序中做的就是:

    // Instantiate the form object
    var form2 = new Form2();
    
    // Load the form object with values
    form2.LoadForm(1, 5, 9);
    
    // Or 
    form2.LoadForm("Foo Bar");
    

    这里的重点是不要让构造函数复杂化,因为单独的方法更容易维护,也更容易遵循。

    【讨论】:

      【解决方案3】:
      public class Form2
      {
      
          public Form2()
          {
              InitializeComponent();
          }
      
          //add your own constructor, which also calls the other, parameterless constructor.
      
          public Form2(int a, int b, int c):this()
          {
              // add your handling code for your parameters here.
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多