0

I have some code below:

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@company", txtCompany.Text);
command.Parameters.AddWithValue("@server", txtServer.Text);
command.Parameters.AddWithValue("@username", txtUserName.Text);
command.Parameters.AddWithValue("@password", txtPassword.Text);

How do i validate empty textboxes making sure that the textboxes are alway populated?

I have tried:

if (string.IsNullOrEmpty(txtCompany.Text))

{
      //do work here
}

else
{

}

However im not sure how i can assign ALL text boxes like this? in a cleaner way which limits the number of lines of code i have to write?

PriceCheaperton
  • 5,071
  • 17
  • 52
  • 94
  • Couldn't get your question! What exactly you want to do? – Faizan Mubasher May 18 '14 at 09:31
  • I need to stop my code from running if there is "" in all the text boxes. – PriceCheaperton May 18 '14 at 09:31
  • possible duplicate of [Loop through Textboxes](http://stackoverflow.com/questions/4863051/loop-through-textboxes) – O. R. Mapper May 18 '14 at 09:32
  • Stopping code from running if textbox is empty! Means you want to terminate application on the fly when there is no data in textboxes. I feel it strange. – Faizan Mubasher May 18 '14 at 09:33
  • Its not a dupe, its a question about validation. – PriceCheaperton May 18 '14 at 09:33
  • 1
    @PriceCheaperton: It's a question about how to access a series of text boxes to perform the same operation on each of them without copy-and-pasting the same code for each text box. At least, your final paragraph sure sounds like that. – O. R. Mapper May 18 '14 at 09:34
  • `if (string.IsNullOrEmpty(txtCompany.Text) || string.IsNullOrEmpty(txtServer.Text) || ...)`. The link @O.R.Mapper gives you can be used to loop over all controls, you can use that if it is relevant. – CodeCaster May 18 '14 at 09:34
  • if i hit "add" on my form it will attempt to insert "" into the database. I simply want assign a validation prompt to stop "" from every being passed into the param. – PriceCheaperton May 18 '14 at 09:35

2 Answers2

2
    private bool ValidateTextBoxes()
    {
        try
        {
            string textBoxData = string.Empty;

            foreach (Control item in this.Controls)
            {
                if (item.GetType() == typeof(TextBox))
                {
                    textBoxData += item.Text;
                }
            }
            return (textBoxData != string.Empty);
        }
        catch { return false; }
    }

    if(ValidateTextBoxes())
    {
         // your code..
    }

Just call the ValidateTextBoxes method before performing database operations e.g

0

Handle the TextBox_Validating for all textBoxes:

public Form1()
{
    InitializeComponent();

    txtCompany.Validating += TextBox_Validating;
    txtServer.Validating  += TextBox_Validating;
    txtUserName.Validating  += TextBox_Validating;
    txtPassword.Validating  += TextBox_Validating;
}
private void TextBox_Validating(object sender, CancelEventArgs e)
{
    TextBox control = sender as TextBox;
    control.Focus();   
    e.Cancel = control.Text == string.Empty;
}

Also you can add this code before executing the command:

bool controlsAreValid = true;

foreach (Control control in this.Control)
{
   if (control is TextBox)
   {
      if (control.Text == string.Empty)
      {
          controlsAreValid = false;
          break;
      }
   }
}
if (!controlsAreValid)
     return;
Meysam Tolouee
  • 569
  • 3
  • 17
  • @jahanviKashyap Yes, I know, But I do not understand the downvote! – Meysam Tolouee May 18 '14 at 09:42
  • i was wondered too. I dint this downvote. you can see i dont even have enough repo to down vote. plus i don't down vote for such awesome answers. – jahanvi Kashyap May 18 '14 at 09:43
  • Just adding this code will not prevent the query to be executed with empty strings. Show how you can use validation to prevent the query from being executed. Something with `ValidateChildren()`. – CodeCaster May 18 '14 at 09:46
  • Looping over all controls and checking whether they're a textbox that contain text does not leverage the `Validating` event. All you need is `if (ValidateChildren()) { DoQuery(); }`. – CodeCaster May 18 '14 at 09:52
  • @CodeCaster But you can put them in a groupBox and loop over groupBox.Controls – Meysam Tolouee May 18 '14 at 09:54
  • Yes, but in that case your `TextBox_Validating` doesn't do anything. Either use the Validating event and the ValidateChildren method (which is the proper approach) _or_ loop over all controls manually. – CodeCaster May 18 '14 at 09:55
  • @CodeCaster Have you ever use Validating event? This event do not allow you to get the focus to another control until you type something in the textBox. Even it does not allow you close the form. So why it does not help? – Meysam Tolouee May 18 '14 at 09:58
  • I'm sorry, you're right. I do have used this event, but not like this, because it's annoying as hell to steal focus like that, causing the user to be unable to even close the form until the validation returns true. But again, if you have the validation events in place like that, you **don't have to loop over the controls anymore**, just call `ValidateChildren()`. – CodeCaster May 18 '14 at 10:04
  • @CodeCaster At first these problem occurs but these problem also have an easy solutions. And because of good validation using validation event I didn't write loop for you at first. – Meysam Tolouee May 18 '14 at 10:08