如何从一种形式访问数据并将其带到另一种形式

How to access data from one form and bring to another

我正在尝试将标签文本拉入同一解决方案中的另一种形式,以便在 if 语句中使用。但是,它似乎并没有从现场提取数据。我正在尝试根据表格 1 中的标签文本更改标签背景的颜色。非常感谢任何帮助。

表格 1:

public void button1_Click(object sender, EventArgs e)
{
    form1 view = new form();
    view.Show();
    view.label1 = label1.Text.ToString();
}

表格 2:

public string label1 { get; set; }

public void Display()
{
    if (label1 == "1")
    {
        for (int i = 0; i < nWinnings.Length; i++)
        {
            Label label = new Label();
            label.BackColor = Color.Red;
            ...
        }
     }
     else
     {
         for (int i = 0; i < nWinnings.Length; i++)
        {
            Label label = new Label();
            label.BackColor = Color.Blue;
            ...
        }
      }
}

标签还有更多内容,但除了颜色变化外,标签工作正常。

这是不正确的:

Label label = new Label();

您无法创建 Labelnew 实例...它与第一个 [=] 中的原始 Label 实例完全没有联系14=],改变上面的任何属性也不会影响原来的


您需要传递对整个 Label:

的引用
// Form 1

public void button1_Click(object sender, EventArgs e)
{
    form1 view = new form();
    view.label1 = label1;
    view.Show();
}

// Form 2

public Label label1 { get; set; }

public void Display()
{
    if (label1.Text == "1")
    {
        for (int i = 0; i < nWinnings.Length; i++)
        {
            label1.BackColor = Color.Red;

            // ... etc, etc

我会限制将对控件的引用传递给其他表单的次数。根据我的经验,当你这样做太多时,代码开始变得很混乱。

如果我的理解是正确的,你有 2 个表格。表格 1 和表格 2。 您在 FORM1 中有一个标签控件 LABEL1。您阅读此文本并将其传递给 FORM2。

在 FORM2 中,您有另一个标签控件 LABEL2,您要更改其背景颜色。

您可以在 FORM2 中声明一个字符串变量。 向 FORM2 添加一个新的构造函数以接受字符串参数,并将此值设置为字符串变量。 在 FORM2 OnLoad 中,您可以检查字符串变量的值并 然后, LABEL2.BackColor = if-else 循环中的 whateverColor。

FORM1 中的类似内容

FORM2 newForm = new FORM2(LABEL1.Text);
newForm.Show();

和 FORM2

private label1String = String.Empty();

public FORM2(string arg)
{
    ...Default Initialization Code...
    label1String = arg;
}

private void ChangeLabel2Color()
{
    if(label1String == "1")
    {
        LABEL2.BackColor = whateverColorYouNeed;
    }
    else
    {
        ...WHATEVER YOU NEED TO DO...
    }
}

代码是我直接写的,可能会有语法错误