公共字符串不想更新

时间:2015-11-07 18:08:13

标签: c# .net string methods public

我有两种形式.. 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”

有谁知道为什么?

1 个答案:

答案 0 :(得分: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