提前处理验证Windows窗体上控件的事件 [英] Advance handling for validating event for controls on windows form
问题描述
我正在设计一个数据输入表格。
用户界面包括:
1.用户名的文本框
2. textbox for用户代码
3. listview显示现有用户的名单
4.添加新用户的按钮
现在,处理2个文本框的验证事件,我写了这段代码:
I am designing a data entry form.
The UI consists of:
1. textbox for user name
2. textbox for user code
3. listview showing a list of names of existing users
4. button to add new user
Now, handling validating event for the 2 textboxes, I have written this code:
void tb_Name_Validating(object sender, CancelEventArgs e)
{
try
{
if(tb_Name.TextLength == 0)
{
tb_Code.Enabled = false;
tb_Name.ForeColor = Color.White;
tb_Name.BackColor = Color.PaleVioletRed;
tb_Name.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
我不允许用户移动到下一个控件,除非用户提供了一个值用户名。
现在,当输入焦点仍在tb_Name并且用户点击listview控件中的项目时出现问题。
一旦用户单击listview项,就会触发验证文本框tb_Name的事件。并且焦点再次保留在文本框本身上并出现错误(更改背景色)。
我想绕过验证事件。但是,我不知道如何告诉c#用户已经移动到tb_Code以外的某些控件。验证事件必须在用户尝试移动以控制tb_Code时发生。
任何帮助都将受到高度赞赏。
谢谢!< br $> b $ b
我尝试了什么:
我试过按顺序Enter,Leave,GotFocus,LostFocus,验证和验证的事件。
此外,我尝试了许多替代方案,但没有一个完美无缺。
I am not allowing user to move to next control unless user has provided a value for the user name.
Now, problem comes when the input focus is still at tb_Name and user clicks on an item in the listview control.
As soon as user clicks on the listview item, validating event for the textbox tb_Name is fired. And the focus is again remained on the textbox itself with an error (changing backcolor).
I want to bypass validating event. But, I dont know how to tell c# that user has moved to some control other than tb_Code. The validating event must occured only when user tries to move to control tb_Code.
Any help will be highly appreciated.
Thank you!
What I have tried:
I tried going through the order of events for Enter,Leave, GotFocus, LostFocus, validating and validated.
Also, I tried many alternatives but none worked perfectly.
推荐答案
如果只想在用户输入tb_Code时进行验证,请使用tb_Code.Enter事件,并在那里移动验证码。
If you want to validate only when the user enters tb_Code, then use the tb_Code.Enter event, and move the validation code there.
这篇关于提前处理验证Windows窗体上控件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!