Connecting Tech Pros Worldwide Forums | Help | Site Map

Are controls empty?

Newbie
 
Join Date: Oct 2009
Posts: 13
#1: Oct 15 '09
I need to check 4 controls (2 combo boxes and 2 text boxes) and make sure they are not empty. I am unsure of how to do this in c#. I need something like...
Expand|Select|Wrap|Line Numbers
  1. If (cbName.Text != String.Empty) AND (cbServer.Text != String.Empty) AND (txtUser.Text != String.Empty) AND (txtPassword.Text != String.Empty)
  2. {
  3. //do something
  4. }
  5. else
  6. {
  7. //do something else
  8. }

Expert
 
Join Date: Jun 2008
Location: Pretoria, South Africa
Posts: 410
#2: Oct 15 '09

re: Are controls empty?


The correct syntax to check for an empty string is:

Expand|Select|Wrap|Line Numbers
  1. string.IsNullOrEmpty("string to test");
For a combo box:

Expand|Select|Wrap|Line Numbers
  1. if(cbName.SelectedItem != null)
The MSDN is a great resource for help on syntax and the .NET framework, it should help you alot in your future study of C#.
Familiar Sight
 
Join Date: Jul 2009
Location: Calgary, Alberta, Canada
Posts: 229
#3: Oct 15 '09

re: Are controls empty?


I think a combo box can have items but still have a null selected item, can't it?

I'd say it would be safer to check if the list of combo box items is empty... but I guess it depends on the settings of the combo box and your definition of empty :D
tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,779
#4: Oct 15 '09

re: Are controls empty?


for your "and" use &&

Expand|Select|Wrap|Line Numbers
  1. if (Text1.Text != string.empty && Text2.Text != string.empty)
  2.  
tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,779
#5: Oct 15 '09

re: Are controls empty?


You really might want to look at the ErrorProvider class.
For just a little more work it's nice to have Error Alerts pop up next to the controls that have problems.

Basically you create a small method for validation, for each control. If the data fails validation an alert (exclamation in a red circle) appears next to the control. This can run when leaving a control for example.

Then you make a method that runs all of your other qualification methods, when you want to validate the entire form, like for an [Apply] button.
Reply