开发者

Windows forms Textbox validation

开发者 https://www.devze.com 2022-12-31 16:05 出处:网络
Please help me in this issue. I am working in windows forms using c#. i have a textbox called textBox1. I want to use validation like without entering anyth开发者_JAVA百科ing in textBox1 the cursor sh

Please help me in this issue. I am working in windows forms using c#. i have a textbox called textBox1. I want to use validation like without entering anyth开发者_JAVA百科ing in textBox1 the cursor should not move to next text field.


On the MouseLeave event of that text box do try this..

if (textBox1.TextLength < 1)
{
  textBox.Focus();
}


Your question isn't exactly clear, to validate that there is indeed something entered in the textbox you can check either:

textBox1.TextLength > 0

or

!String.IsNullOrEmpty(textBox1.Text)


This is not an approach I recommend, but you can handle the textbox's Validating event and cancel (setting the focus back to the textbox) if nothing has been entered, like this:

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text.Trim() == "")
    {
        e.Cancel = true;
    }
}

This will work, but it is certain to annoy the users. A better approach to validation is to let users enter or not enter text in various textboxes as they choose, and then validate everything at once when the user submits the form.

0

精彩评论

暂无评论...
验证码 换一张
取 消