【发布时间】:2018-05-21 19:04:56
【问题描述】:
这个问题建立在我 4 天前提出的问题 complex if statement in an text changed event 的基础上。我尝试了很多,以便不会出现问题System.ArgumentOutOfRangeException。出现问题是因为 if 语句位于文本更改事件中并检查了 8 个字符,这些字符在运行时出现。因此,并非所有字符都是立即可用的,而是由用户输入动态生成的。这就是问题开始的地方,每次文本框中的文本发生变化时,都会触发事件,同时程序立即需要 8 个字符,并在逻辑上给出错误消息System.ArgumentOutOfRangeException。为了解决这个问题,我将洞 if 语句放在 try-catch 块中。现在它可以工作了,但这是一个好习惯吗?还有其他/更好的解决方案吗?这是我的代码的摘录:
private void txtBoxEingabe_TextChanged(object sender, EventArgs e)
{
axAcroPDF1.LoadFile("DONTEXISTS.pdf");
radioButton1.Visible = false;
radioButton2.Visible = false;
string text = txtBoxEingabe.Text.Substring(0, txtBoxEingabe.TextLength);
try
{
if (text.Substring(0, 3) == "SEH" && text.Substring(3, 1) == "M" && Convert.ToInt32(text.Substring(4, 4)) <= 2999 && (text.Substring(8, 1) == "H" || text.Substring(8, 1) == "R"))
{
radioButton1.Visible = true;
radioButton2.Visible = true;
radioButton1.Text = "1. Document";
radioButton2.Text = "2. Document";
this.radioButton1.CheckedChanged += RadioBtnChangedDC1;
this.radioButton2.CheckedChanged += RadioBtnChangedDC1;
}
}
catch
{
}
private void RadioBtnChangedDC1(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
axAcroPDF1.LoadFile("C:\Doc1.pdf");
axAcroPDF1.gotoFirstPage();
Screensize = 100;
axAcroPDF1.setZoom(Screensize);
axAcroPDF1.setShowScrollbars(true);
axAcroPDF1.setShowToolbar(false);
}
else if (radioButton2.Checked == true)
{
axAcroPDF1.LoadFile("C:\Doc2.pdf");
axAcroPDF1.gotoFirstPage();
Screensize = 100;
axAcroPDF1.setZoom(Screensize);
axAcroPDF1.setShowScrollbars(true);
axAcroPDF1.setShowToolbar(false);
}
}
这个程序应该是一个可以显示数百个文档的查看器。
【问题讨论】:
-
为什么在运行总是会导致异常的代码之前不检查长度?
-
这是一个好习惯吗?不,不是。应该通过检查来防止您期望的错误。盲目地捕捉总是一个可怕的想法,因为它会让你对问题视而不见..
标签: c# if-statement try-catch user-input textchanged