简体   繁体   English

C#:如何在TextBox派生的类中从事件处理程序引发异常?

[英]C#: How can I raise an exception from an event handler in a class derived from TextBox?

I am developing a numeric text box, a control derived from TextBox that will only accept numeric input. 我正在开发一个数字文本框,它是一个从TextBox派生的控件,它将仅接受数字输入。 (Yes, I know there's lots of these, but the ones I saw are a lot more complicated than they need to be.) My class overrides OnKeyDown() and checks to see if the newly entered text can be converted to a number, and if that number is within specified limits. (是的,我知道有很多东西,但是我看到的比它们要复杂得多。)我的类重写OnKeyDown()并检查是否可以将新输入的文本转换为数字,并且如果该数字在指定的范围内。 If the number is outside the limits, then an InvalidOperationException is raised. 如果数字超出限制,则引发InvalidOperationException。

When I tested this control on a form, I expected to see a unhandled exception message pop up, but it didn't. 当我在窗体上测试此控件时,我希望看到未处理的异常消息弹出,但事实并非如此。 I think this is because unhandled exceptions thrown from event handlers are ignored. 我认为这是因为事件处理程序抛出的未处理异常会被忽略。 But since this exception is being thrown from inside the text box, there's no place on my form where I can catch this exception. 但是由于此异常是从文本框内引发的,所以在窗体上没有地方可以捕获此异常。

I suppose I can add an event to my control named BadValue, but then I'd have to remember to add a handler for that event wherever I used that control. 我想我可以将一个名为BadValue的事件添加到我的控件中,但是无论何时使用该控件,我都必须记住为该事件添加一个处理程序。 I want to be able to rely on standard exception processing, but I don't know how. 我希望能够依靠标准异常处理,但是我不知道如何。

Thank you for your thoughts. 谢谢你的想法。

if u don't want the textbox to allow user to write numbers in it u can easily use a masked text box with a numeric mask if ur ok with the user writing numbers then showing an error message with invalid value u may use this try catch code 如果您不希望文本框允许用户在其中输入数字,则可以轻松地使用带数字掩码的带掩码文本框,如果您可以正确输入用户的数字,则显示错误值无效的错误消息,您可以使用此try catch码

       try
        {
            int x = int.Parse(textBox1.Text);
        }
        catch
        {
            MessageBox.Show("The value is invalid");
        }

this will try to parse the value as int ..if it's not then it throw an exception u can use any other numeric data type of course depending on the value 这将尝试将值解析为int ..如果不是,则抛出异常,您当然可以根据值使用任何其他数字数据类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM