如何在C#中将Form1值传递给Form3

时间:2014-09-28 10:08:12

标签: c# winforms return-value

如何将 form1 的值直接传递给 Form3

Form1 中,我有按钮和名为 txtUsername Textbox

   public string username = string.Empty;
 private void LoginBT_Click(object sender, EventArgs e)
      {
         username = txtUsername.Text;
         Form3 form  = new Form3(username);

         Form2 frm = new Form2();
         frm.Show();
         this.Hide
}

From2 我有这个

 private void Button_Click(object sender, EventArgs e)
      {
            Form3 form = new Form3();
            form.Show();
            this.Hide();
       }

Form3

public string Name;
        public Form3(string CName)
                {

                    InitializeComponent();
                    Name= Cname;
                }

private void frmTicketandCottages_Load(object sender, EventArgs e)
        {
      MessageBox.Show(Name); 
         }

显示文字。

但是当我显示文本时,我只得到一个空文本

还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

这太简单了: 在Button_Click中,您没有通过Name

Form3 form = new Form3();

通过声明

Username传递给 Form2
 public string username

或在Form3中的构造函数中:

public string Name;
    public Form2(string CName)
            {

                InitializeComponent();
                Name= Cname;
            }

然后

  public string username = string.Empty;

     private void LoginBT_Click(object sender, EventArgs e)
          {
             username = txtUsername.Text;
             Form3 form  = new Form3(username);

             Form2 frm = new Form2(username);
             frm.Show();
             this.Hide
    }

你必须像这样传递Name

 Form3 form  = new Form3(username);

答案 1 :(得分:0)

如果要直接将值传递给form3,为什么还需要转到表单2?无论如何你可以这样做......

Form1中:

     private void LoginBT_Click(object sender, EventArgs e)
     {
     username = txtUsername.Text;


     Form2 frm = new Form2(username);
     frm.Show();
     this.Hide
     }

窗口2:

    string Name;
    public Form2(string CName)
            {

                InitializeComponent();
                Name= Cname;
            }

   private void Button_Click(object sender, EventArgs e)
  {
        Form3 form = new Form3(Name);
        form.Show();
        this.Close();
   }

form3:

    string Name;
    public Form3(string CName)
            {

                InitializeComponent();
                Name= Cname;
            }

    private void frmTicketandCottages_Load(object sender, EventArgs e)
            {
                MessageBox.Show(Name); 
            }