c# - 我如何才能在我的以下代码没有异常(exception)的情况下再次关注文本框?

标签 c#

我有一个表单,我按照下面的说明对我的文本框进行了验证。对于下面的代码,当我按下“清除”按钮时,文本框被清空,然后,当我试图专注于任何文本框(即,我试图点击任何文本框)输入一些新文本,然后发生 InvalidCastException .. 为什么这样???

namespace ex_validation
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                txtuserid.Validating += new CancelEventHandler(Dovalidation);
                txtpassword.Validating += new CancelEventHandler(Dovalidation);
                txtage.Validating += new CancelEventHandler(Dovalidation);
                btnnextform.Validating += new CancelEventHandler(Dovalidation);
                btnclear.Validating += new CancelEventHandler(Dovalidation);
            }
            public void Dovalidation(object sender, CancelEventArgs e)
            {
                TextBox t = (TextBox)sender;// " EXCEPTION OCCURS AT THIS LINE "
                if (t.Text=="")
                {
                    t.BackColor = System.Drawing.Color.Yellow;// sets the backcolor of the textbox if found empty
                    e.Cancel = true;// cancel all other events unless user enters something in that relevant textbox
                }
                else
                    t.BackColor = System.Drawing.Color.White;
            }

            private void txtage_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                {
                    e.Handled = true;
                }
            }

            private void txtage_Leave(object sender, EventArgs e)
            {
                if (txtage.Text == "")
                    MessageBox.Show("Age field cannot be left blank");
                else
                {
                    int x = System.Convert.ToInt16(txtage.Text);
                    if (x < 1 || x > 100)
                    {
                        MessageBox.Show("Age cannot be above 100 OR below 1", "Prompt Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtage.Clear();
                        txtage.Focus();
                    }
                }
            }

            private void btnnextform_Click(object sender, EventArgs e)
            {
                Form2 f = new Form2();
                f.Show();
            }

            private void btnclear_Click(object sender, EventArgs e)
            {
                txtuserid.Text = (string)"";
                txtpassword.Text = (string)"";
                txtage.Text = (string)"";
            }
        }
    }

最佳答案

您将 Dovalidation 注册到 other 控件上的事件而不是 TextBox 因此转换失败,即 btnnextformbtnclear.

不要在转换失败的情况下显式转换(或者这样做并处理可能的异常)。有两种简单的方法可以预先防止无效转换:

1) 使用 as 进行空检查:

TextBox t = sender as TextBox;

if (t != null)
{
    // We have a textbox.
}

Button b = sender as Button; // etc

2) 使用 is ( doc ) 测试类型:

if (sender is TextBox)
{
    TextBox t = (TextBox)sender;
}

但是你需要像往常一样进行转换,所以在这种情况下我倾向于坚持使用 as

as operator类似于显式转换,但如果无法进行转换,它会返回 null 而不是抛出异常。

Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.


或者:

然而,也就是说,如果您需要对按钮和文本框进行不同的验证,您可能只想使用另一种单独的验证方法 - 这将产生一组更简单和更小的方法,而不是一个尝试做所有事情的方法。

关于c# - 我如何才能在我的以下代码没有异常(exception)的情况下再次关注文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892379/

相关文章:

c# - 您可以在类型上而不是在类型的实例上拥有扩展方法吗?

c# - 让程序在每次引发异常时发出蜂鸣声

c# - WPF TextBlock 绑定(bind)到字符串

c# - Powershell 结果集未在 C# 中获取

c# - 如何将 byte[] 数组加载到 C# 中的结构中?

c# - Graphics.DrawIcon 忽略比例变换?

C# 获取 2 个 HTML 标签之间的字符串

c# - 自动更新版本号

c# - 在 nHibernate 中过滤连接

C#将按位运算符作为参数传递