如何创建一个If语句来检查textBox1.Text是否包含字符串reply = client.DownloadString(address);正常吗?

时间:2018-04-18 18:35:54

标签: c# forms winforms visual-studio

我正在尝试创建一个按钮,用于检查textBox1.Text是否包含我在Pastebin上的原始文本文件中的任何文本以进行测试。

这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        WebClient client = new WebClient();
        string reply = client.DownloadString("https://pastebin.com/raw/0FHx1t5w");
    }

和我的按钮

private void button1_Click(object sender, EventArgs e)
{
    string textbox = textBox1.Text;

    // Compile error on next line: 
    if (textbox.Contains(reply))
    {
    }
}

字符串reply标记为红色,并显示:

  

名称'回复'在当前上下文中不存在

是因为.Contains不支持字符串检查吗?

2 个答案:

答案 0 :(得分:3)

这是一个范围问题。 GetByIdreply的构造函数中定义。退出构造函数后,Form1变量不再有效。

您可以在类级别而不是在方法中声明变量。

reply

然后,您将能够通过按钮单击事件处理程序访问它。

答案 1 :(得分:0)

将您的代码更改为:

public partial class Form1 : Form
{
    //Now its a field, rename it appropriately later
    private string reply;

    public Form1()
    {
        InitializeComponent();



        WebClient client = new WebClient();
        reply = client.DownloadString("https://pastebin.com/raw/0FHx1t5w");



    }