[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


First Time Error Provider Question

Posted on 2007-10-04
Medium Priority
Last Modified: 2013-11-26

This is the first time I will be using an error provider, so bear with me if the question is of a beginner level.
How do I add an error provider to a textbox on my Winform application? I have Multiple textboxes that I want to make sure that the right entries are made before the submit button is clicked. Do I have to add an error provider for all my textboxes?

Any help would be appreciated.

Question by:ALawrence007
  • 5
  • 4

Assisted Solution

joesthebighmoe earned 2000 total points
ID: 20016316
<<<How do I add an error provider to a textbox on my Winform application?>>>
ErrorProvider myEP = new ErrorProvider();
myEP.SetError(textBox1, "Doh!");

By default it will put the error icon to the right of the text box. The Error Provied class has various properties so you can change this if you want.

<<Do I have to add an error provider for all my textboxes>> I think you should yes.

Can you envisiona routine like this?
private void AssignErrorToControl(Control ControlToAddErrorTo, string ErrorMsg)
      ErrorProvider myEP = new ErrorProvider();
      myEP.SetError(ControlToAddErrorTo, ErrorMsg);

If you had this, then all code that validates things would just call it.
For example (in psuedo code)
if txtName is bad then AssignErrorToControl(txtName, "Bad Name.")
if txtAge is bad then AssignErrorToControl(txtName, "Bad Age.")



Expert Comment

ID: 20016329
I'll monitor this for awhile, so let me know if you need follow up help or the example in a different language.

Author Comment

ID: 20016467

That worked perfect, but the Error sign does not disappear if I have the right info in there.
Please note that with startup I load my textbox with a '0'. The error shows up from the start.
Here is my code and how I changed it.

If IPBox.Text = "" Then
AssignErrorToControl(IPBox, "Please Enter a Price")
End If
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.


Assisted Solution

joesthebighmoe earned 2000 total points
ID: 20016743
Oooooooh, I see. Well, it appears you might have to create an Error Control per input. I hoped we could have avoided that.
Can I recommend (and I know this is not a right or wrong but rather preference based on experience) that you simplify things by not checking validity until the user is done. What you are doing is complicating things for yourself, starting with dealing with you wanting to prefill your inputs with what amounts to invalid values. When the user clicks "OK" or "Submit" or whatever, call a routine that first clears all errors from your error providers and then sets up any new ones.
So in your declarations you can declare ErrorProviders for each input.
dim txtFirstNameErrProv = new ErrorProvider()
dim txtlLastNameErrProv = new ErrorProvider()
When the user is done entering data and they click OK, have a method called ValidateInput. This routine first clears the providers.
txtlLastNameErrProv .Clear()
It then does its checks and adds the appropriate messages.
txtlLastNameErrProv.SetError(txtFirstName, "First Name cannot be blank")
txtlLastNameErrProv.SerError(txtlLastName, "Your last name can only contain letters!")

Whatt-a-ya think?

Author Comment

ID: 20018584
That sounds like the way to go then. How would I do that? I mean how and where would I add the code? Would I still keep my routine like you said above? or would I add all the code in the Textbox change method?

Thanks joesthebighmoe! This has helped me a lot this far!

Accepted Solution

joesthebighmoe earned 2000 total points
ID: 20021507
Here's what I would do, tell me if am not making sense, or if you think it should be done a different way:
I played around with the ErrorProvider last night and found that you could use just one for all your controls in many cases.
Let's say you had a user interface form called myForm with 3 inputs: txtFirstName, txtLastName and cbStatus (Combo box with Status objects). (I am also assuming you are using Visual Studio 2005, correct me if I am wrong.) The form also has a button called btnSaveChanges.
At the top of your form class code, just under this line "Public Class myForm" instantiate an Error Provider
Private m_ErrProvider As ErrorProvider = New ErrorProvider()

In the event handler for the btnSaveChanges click event make a call to a routine called something like HandleSaveChanges. (This is a good place to put exception handling also since it is an Entry Point into your application.)

Private Sub btnSaveChanges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveChanges.Click
  Catch ex As Exception
    MessageBox.Show("There's a problem:" & ex.ToString(), "Doh!")
  End Try
End Sub
Here's what the code might look like in Handle_SaveChanges: (To handle the fact the user wants to save changes we need to validate that everything is cool with the user's inputs and if they are have the inputs saved.
''' <summary>
''' Handles the fact that the user wants to save the changes
''' </summary>
Private Sub Handle_SaveChanges()
  Dim IsEverythingCool As Boolean
  If IsEverythingCool = True Then
  End If
End Sub

The CheckUserInputs routine might look like this:
Private Sub CheckUserInputs(ByRef o_IsEverythingCool As Boolean)

  o_IsEverythingCool = True 'until proven otherwise
  If txtFirstName.Text.Trim() = "" Then
    o_IsEverythingCool = False
    m_ErrProvider.SetError(txtFirstName, "First Name cannot be blank")
  End If
  If txtLastName.Text.Trim() = "" Then
    o_IsEverythingCool = False
    m_ErrProvider.SetError(txtLastName, "Last Name cannot be blank")
  End If
  If cbStatus.SelectedItem = Nothing Then
    o_IsEverythingCool = False
    m_ErrProvider.SetError(cbStatus, "A Status must be chosen")
  End If
End Sub
Granted, you probably would have CheckUserInputs call individual routines for each input since each one undoubtedly has multiple checks besides just being blank.
Your SaveChanges routine would do what ever it is you plan to do with the data, I assume save it in the system's permanent storage.

I hope this makes sense,


Author Comment

ID: 20022003

That worked perfect! That was exactly what I wanted. I have one more question, and hope that you will be able to help me:

How can I validate something like Price being a certain way i.e 12.50 and not 12....50
Stupid example, but this happened 2 days ago with someone pressing the . twice and gave an SQL error.

Thanks for the help this far!

Assisted Solution

joesthebighmoe earned 2000 total points
ID: 20022073
What is a price in your business? A decimal I am guessing.
I am assuming the user enters a string eh?
There is a method on the decimal type called TryParse. Your code would look something like this.
Dim sPrice As String
sPrice = txtPrice.Text.Trim()
Dim decPrice As Decimal
If (Decimal.TryParse(sPrice, decPrice) = True) Then
  'woohoo, good number
  'doh, price is invalid
End If

Author Comment

ID: 20022257
Thanks Joe!

I learned a lot with this post!

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses
Course of the Month19 days, 13 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question