【问题标题】:Public string doesn't want to update公共字符串不想更新
【发布时间】:2023-04-01 23:10:01
【问题描述】:

我有两个表单.. Form1.cs 和 TwitchCommands.cs

我的 Form1.cs 有一个全局变量

public string SkinURL { get; set;}

我希望该字符串成为 TwitchCommands.cs 中文本框的值

这是 TwitchCommands.cs 中的代码,应该在 Form.cs 中设置公共字符串“SkinURL”

private void btnDone_Click(object sender, EventArgs e)
        {
            if (txtSkinURL.Text == @"Skin URL")
            {
                MessageBox.Show(@"Please enter a URL...");
            }
            else
            {
                var _frm1 = new Form1();
                _frm1.SkinUrl = txtSkinURL.Text;
                Close();
            }
        }

这是 Form1.cs 中尝试访问字符串“SkinURL”的代码

else if (message.Contains("!skin"))
                {
                    irc.sendChatMessage("Skin download: " + SkinUrl);
                }

假设 txtSkinURL.text = "www.google.ca" 我在 Form1.cs 中调用命令

它返回“皮肤下载:”而不是“皮肤下载:www.google.ca”

有人知道为什么吗?

【问题讨论】:

  • 因为您正在创建 Form1 的新实例。具有自己的 SkinURL 变量的实例,当然该变量还没有收到您对 Form1 的第一个实例所做的更改
  • 那么我将如何访问 SkinURL 变量?

标签: c# .net string methods public


【解决方案1】:

因为您正在创建 Form1 的新实例。具有自己的 SkinURL 变量的实例。正是这个变量从您的第二个表单接收文本。您的代码没有触及 Form1 的第一个实例中的变量

如果您在新实例上调用 Show 方法,这很容易证明

....
else
{
    var _frm1 = new Form1();
    _frm1.SkinUrl = txtSkinURL.Text;
    _frm1.Show();
}
...

在您的场景中,我认为您需要将全局变量放在 TwitchCommands.cs 表单中,当您调用该表单时,您可以将其读回

在 TwitchCommands.cs 中

public string SkinURL { get; set;}
private void btnDone_Click(object sender, EventArgs e)
{
    if (txtSkinURL.Text == @"Skin URL")
    {
        MessageBox.Show(@"Please enter a URL...");
    }
    else
    {
        SkinURL = txtSkinURL.Text;
        Close();
    }
}

在您的 Form1.cs 中,当您调用 TwitchCommands.cs 表单时

TwitchCommands twitchForm = new TwitchCommands();
twitchForm.ShowDialog();

string selectedSkin = twitchForm.SkinURL;
... and do whatever you like with the selectedSkin variable inside form1

【讨论】:

  • 谢谢。那是我的错误。我在做 twitchForm.Show();而不是 twitchForm.ShowDialog();
猜你喜欢
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2011-12-10
  • 1970-01-01
  • 2011-11-26
  • 2011-02-15
  • 1970-01-01
相关资源
最近更新 更多