无法使用按钮清除文本框
问题描述:
每当我尝试清除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);
}
答
Firzanah, 当清除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);
}
答
什么是有可能发生的是,明确事件被触发正确的,然后你的onChange事件也触发,发送一个空字符串给你的代码,这是异常来自哪里。
我建议围绕你的代码尝试......捕捉块的方式,异常的来源更清晰或作为@cody灰色建议只需使用调试器。
+1
Try/Catch块不会使例外的来源更加清晰。如果有的话,他们混淆它。调试器很容易让你找到异常的来源。 –
答
错误会genereate因为你没有什么值转换为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="";
}
尝试没有办法,这个代码重现您的问题。这两个函数调用都没有'startIndex'参数。 –