如何使用{get;从form1到form2的变量组;}?

时间:2012-05-09 10:13:22

标签: c# winforms

所有

我是C#的新手。我知道这是一个非常受欢迎的问题。但我不明白。我知道有一个错误,但在哪里? 例如 - 代码Form1的第一部分包括私有变量测试,我需要在Form2中获取此变量的值。错误在哪里?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string test = "test this point";
            Form2 dlg = new Form2();
            dlg.test = test;
            dlg.Show();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public string test { get; set; }

        public Form2()
        {
            InitializeComponent();
            label1.Text = test;
        }
    }
}

4 个答案:

答案 0 :(得分:3)

在您的Form2中,您正在使用公共属性,因为它是public您可以通过form1中的对象分配它。例如:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 dlg = new Form2();
            dlg.test = "test this point";
            dlg.Show();
        }

在表单2中有两种方法可以使用它,如果你只是想让它只设置标签的text属性,那么这将是最好的:

public partial class Form2 : Form
    {
        public string test 
        { 
           get { return label1.Text; }
           set { label1.Text = value ;} 
        }

        public Form2()
        {
            InitializeComponent();
        }
    }

在属性的setter中,如果需要,您也可以调用函数。

答案 1 :(得分:1)

答案 2 :(得分:0)

您没有在方法中的任何位置使用字符串测试。试试这个:

private void button1_Click(object sender, EventArgs e)
{
    Form2 dlg = new Form2();

    dlg.Test = "test this point";

    dlg.Show();
}

了解如何将值分配给Form2对象Test上的属性dlg

注意:我对属性Test使用了captial,因为这是对属性名称样式的一般共识。

答案 3 :(得分:0)

test是Form2可用的属性(更好的情况是测试),而string test的范围仅限于Form1的点击事件。除非您指定属性,否则它与属性无关。

Form2 dlg = new Form2();
dlg.test = test; // this will assign it
dlg.Show();

现在Form2属性已获得用于在Label

中显示相同值的值