【问题标题】:How to get variable from form1 to form2 with { get; set;}?如何使用 { get; 从 form1 获取变量到 form2放;}?
【发布时间】:2012-05-09 10:13:21
【问题描述】:

全部。

我是 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;
        }
    }
}

【问题讨论】:

  • 那么你必须将它分配给Form2 test 属性,你所拥有的是一个独立的字符串,它与Form2 的属性无关。需要Form1 中的dlg.test = test;

标签: c# winforms


【解决方案1】:

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

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

在表格2中有几种使用方法,如果你只想设置标签的文本属性,这将是最好的:

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

        public Form2()
        {
            InitializeComponent();
        }
    }

如果需要,您还可以在属性的设置器中调用函数。

【讨论】:

  • 好的。但是如何在Form2中使用这个变量。我更改了代码,但什么也没发生?!
【解决方案2】:
【解决方案3】:

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

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

    dlg.Test = "test this point";

    dlg.Show();
}

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

注意:我对属性 Test 使用了大写字母,因为这是属性名称样式的普遍共识。

【讨论】:

    【解决方案4】:

    test 是一个可用于Form2 的属性(最好是测试),而string test 仅适用于Form1 的点击事件。除非您分配它,否则它与该属性无关。

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

    现在Form2 属性已获得将用于在Label 中显示相同的值

    【讨论】:

    • 谢谢。但是Form2中如何使用这个变量呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多