e在当前上下文中不存在

编程入门 行业动态 更新时间:2024-10-26 08:32:08
本文介绍了e在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用了两个文本框,例如txtSerial和txtID,我只想输入 数字0到9.可以.但是我想在其他私有功能的按键中使用相同的代码.但是不存在e处理程序.现在我该如何解决这个问题?我需要在其他私有函数中使用e处理程序.请更新我 解决方案.

I used two textbox like name txtSerial and txtID where I want to type only number 0 to 9. This is ok. But I want to use same code in keypress in a other private function. But there e handler doesn''t exist. Now how can I solve this problem? I need to use e handler in others private function. Please update me a solution.

private void txtSerial_KeyPress(object sender, KeyPressEventArgs e) { number_handler(); } private void txtID_KeyPress(object sender, KeyPressEventArgs e) { number_handler(); } private void number_handler() { char var = e.KeyChar; if (var == 8) e.Handled = false; else if (var < '0' || var > '9') e.Handled = true; }

推荐答案

哇!您认为在number_handler中定义e的位置是什么?例如,向此方法添加参数KeyPressEventArgs e. 等一下.您真的了解您要写什么吗?不要使用var-这是一个关键字.您的代码将不会编译,因为8不是char,您可以使用"\ U + 0008"将其设置为字符,与KeyPressEventArgs.KeyChar进行比较.无需将Handled分配为false-这是其初始值;仅在需要时分配为true.
—SA
Wow! And where do you think e is defined in number_handler? Add a parameter KeyPressEventArgs e to this method, for example. Wait a minute. Do you really understand what are you trying to write? Don''t use var — this is a keyword. Your code won''t compile because 8 is not a char, you can use ''\U+0008'' to make it a character, as comparison with KeyPressEventArgs.KeyChar requires. No need to assign Handled to false — this is its initial value; only assign to true when required.
—SA

在两个KeyPress处理程序中,"e"是一个参数,您不会传递给number_handler方法. 因此,它不可用,因为编译器不会检查调用什么并使变量在链中可用. 如果在number_handler中需要"e",则将其作为参数传递,或者更好,将其传递给e.KeyChar,并根据其是否处理返回真或假.这样,它不需要知道它是从事件处理程序中调用的,它可以是更通用的方法. In both KeyPress handlers, "e" is a parameter, which you do not pass to the number_handler method. Hence, it is not available, since the compiler does not check what calls what and make variables available in a chain. If you need "e" in number_handler, then pass it through as a parameter, or better, hand it e.KeyChar and have it return true or false depending on whether it handled it or not. That way, it does not need to know it is called from an event handler, and can be a more generic method.

哇!解决方案3极大地帮助了我.但是number_handler()中有一个错误. Wow! solution 3 is greatly helped me. But there e is mistake in number_handler(). private void txtSerial_KeyPress(object sender, KeyPressEventArgs e) { number_handler(e); } private void txtID_KeyPress(object sender, KeyPressEventArgs e) { number_handler(e); } private void number_handler(KeyPressEventArgs e) { char var = e.KeyChar; if (var == 8) e.Handled = false; else if (var < '0' || var > '9') e.Handled = true; }

更多推荐

e在当前上下文中不存在

本文发布于:2023-11-09 15:09:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   中不

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!