Textbox validation in a Windows Form

后端 未结 3 1445
不思量自难忘°
不思量自难忘° 2021-01-18 05:52

I want to put a validation that the user always enters a value in the textbox before submiting the form. But the check that I have put allows user to enter white spaces and

相关标签:
3条回答
  • 2021-01-18 06:16

    in NET4.0 there is a nice function

     if(string.IsNullOrWhiteSpace(textBox1.Text))
    {
       //raise your validation exception
    }
    else {
      //go to submit
    }
    
    0 讨论(0)
  • 2021-01-18 06:16

    It can be easily be done using error provider here is the code.Error Provider you can find in your toolbox.

        private void btnsubmit_Click(object sender, EventArgs e)
                {
    
                    if (string.IsNullOrEmpty(txtname.Text))
                    {
    
                        txtname.Focus();
                        errorProvider1.SetError(txtname, "Please Enter User Name");
                    }
    
                    if (string.IsNullOrEmpty(txtroll.Text)) {
                        txtroll.Focus();
                        errorProvider1.SetError(txtroll, "Please Enter Student Roll NO");
                    }
    }
    

    Here is output image

    0 讨论(0)
  • 2021-01-18 06:18

    You can make your own custom validation function. This may be very naive, but somehow it will work.

    private bool WithErrors()
    {
        if(textBox1.Text.Trim() == String.Empty) 
            return true; // Returns true if no input or only space is found
        if(textBox2.Text.Trim() == String.Empty)
            return true;
        // Other textBoxes.
    
        return false;
    }
    
    private void buttonSubmit_Click(object sender, EventArgs e)
    {
        if(WithErrors())
        {
            // Notify user for error.
        }
        else
        {
            // Do whatever here... Submit
        }
    }
    
    0 讨论(0)
提交回复
热议问题