【问题标题】:How can I make an If statement to check if textBox1.Text contains the string reply = client.DownloadString (address); properly?如何制作 If 语句来检查 textBox1.Text 是否包含字符串 reply = client.DownloadString (address);适当地?
【发布时间】:2018-09-29 02:40:58
【问题描述】:

我正在尝试制作一个按钮,用于检查 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被标记为红色并表示:

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

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

【问题讨论】:

  • 这是因为变量“reply”只存在于Form1构造函数的上下文中,因为它是局部变量(你在那里声明的)。使其成为类字段或声明它并下载 button1_Click 方法中的值。
  • 另外,您需要使用TextboxText 属性(而不是Textbox 本身)调用Contains。并且,如果 first 字符串包含 second 字符串,Contains 将返回 true。在您的情况下,听起来您想检查文本框文本是否包含在原始文本中。如果是这种情况,您将使用if (reply.Contains(textbox.Text))
  • 你好 Rufus L,当我单击带有“if (textbox.Contains(reply ))”。我将回复字符串打印到控制台,这很好。
  • 显示更新后的代码。同样,if (textbox.Contains(reply)) 不正确,因为textbox 没有Contains 的定义。您需要使用if (textbox.Text.Contains(reply))

标签: c# forms winforms visual-studio


【解决方案1】:

这是范围问题。 replyForm1 的构造函数中定义。一旦构造函数退出,reply 变量就不再有效。

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

public partial class Form1 : Form
{
    // Declare it here
    private string reply;

    public Form1()
    {
        InitializeComponent();

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

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

【讨论】:

    【解决方案2】:

    把你的代码改成这样:

    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");
    
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2018-03-16
      • 1970-01-01
      • 2017-10-02
      • 2021-12-08
      • 2011-03-29
      • 2020-01-15
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多