【问题标题】:Textbox cannot be cleared with button press按下按钮无法清除文本框
【发布时间】:2017-09-11 03:43:37
【问题描述】:

每当我尝试清除 textBox2 时,我都会收到一条错误消息。我该如何解决这个问题?

private void textBox2_TextChanged(object sender, EventArgs e)
    {
        string HexKey = this.textBox2.Text;
        if(textBox2.Focused)
        int key = Convert.ToInt32(HexKey, 16);
    }

private void button2_Click_1(object sender, EventArgs e)
    {
        textBox2.Clear();
    }

[错误]: System.ArgumentOutOfRangeException: '索引超出范围。必须是非负数且小于集合的大小。 参数名称:startIndex'

【解决方案】:

private void textBox2_TextChanged(object sender, EventArgs e)
    {
        string HexKey = this.textBox2.Text;
        if(textBox2.Focused) //add this line in
        int key = Convert.ToInt32(HexKey, 16);
    }

【问题讨论】:

  • 这段代码无法重现您的问题。这些函数调用中的任何一个都没有startIndex 参数。

标签: c# winforms textbox


【解决方案1】:

会产生错误,因为您没有将任何值转换为 int32 并且 请尝试使用此代码

private void textBox2_TextChanged(object sender, EventArgs e)
{
    int n,key;
    if (!int.TryParse(txtBox2.Text, out n))
        return;
    else
       key = Convert.ToInt32(txtBox2.Text, 16);
}

private void button2_Click_1(object sender, EventArgs e)
{
   textBox2.Text="";
}

【讨论】:

    【解决方案2】:

    菲莎娜, 当您清除 textBox2 时,将触发 TextChanged 事件。由于此时您的文本框中将没有任何内容,因此当您尝试将任何内容都转换为 int32 时会发生错误。要解决此问题,请将if(textBox2.Focused) 条件添加到您的更改事件中,或者更好的是,只需检查您所拥有的是一个 int 开头:

    private void textBox2_TextChanged(object sender, EventArgs e)
            {
                int n;
                bool isNumeric = int.TryParse(textBox2.Text, out n);
                if (!isNumeric) return;
                string HexKey = textBox2.Text;
                int key = Convert.ToInt32(HexKey, 16);
            }
    

    【讨论】:

      【解决方案3】:

      可能发生的情况是 clear 事件正确触发,然后您的 onChange 事件也立即触发,向您的代码发送一个空字符串,这是异常的来源。

      我建议您使用 Try...Catch 块包围您的代码,以使异常的起源更清楚,或者像 @cody gray 建议的那样简单地使用调试器。

      【讨论】:

      • Try/Catch 块不会使异常的起源更加清晰。如果有的话,他们会混淆它。调试器可以让您轻松找到异常的来源。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多