i have textboxes that needs to have a value before passing it to database.

How to do this? I'm new to windows form validation..

I know of something

if(textBox1.Text=="")
{
//do something
}

is this the right valdiation for windows form?

Recommended Answers

All 13 Replies

Yes, it is a right validation.
But you can also write

if (textbox1.Text.equals(string.Empty))
{
//do stuff
}

I read error providers just now and i made a empty string and numeric validation

private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            bool stat = ValidateNames();

            if (stat == true)
            {
                errorProvider1.SetError(textBox1, "Enter something in textbox1");
            }
            else
            {
                errorProvider1.SetError(textBox1, "");
            }
        }

        private bool ValidateNames()
        {
            if (textBox1.Text == string.Empty)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void textBox2_Validating(object sender, CancelEventArgs e)
        {
            bool stat = ValidateNumbers();

            if (stat == true)
            {
                errorProvider1.SetError(textBox2, "Numbers only");
            }
            else
            {
                errorProvider1.SetError(textBox2, "");
            }
        }

        private bool ValidateNumbers()
        {
            if (textBox2.Text == string.Empty)
            {
                return true;
            }
            char[] testArr = textBox2.Text.ToCharArray();
            bool stat = false;
            for (int i = 0; i < testArr.Length; i++)
            {
                if (!char.IsNumber(testArr[i]))
                {
                    stat = true;
                }
            }
            return stat;
        }

This works though I'm kinda confused on to validate all of the controls at the same time using a button click..

The Control.Validating event is only raised when the control loses focus so to validate all controls you would have to iterate through them giving them each focus.
If you have created each validation method to return a bool (as you show above) then you can check the status of each control in the buttons click event seperately from your errorProvider:

private void button1_Click(object sender, EventArgs e)
    {
        //call each validation method and store results
        bool vName = ValidateNames();
        bool vNumber = ValidateNumbers();

        //if all results return true then form is valid
        if (vName && vNumber)
        {
            //form valid, do stuff
        }
        else
        {
            //form not valid, alert user
        }
    }

I tried that

private void Validateform()
        {
            bool name = ValidateNames();
            bool number = ValidateNumbers();

            if (name && number)
            {
                MessageBox.Show("SUCCESS");
                SqlCommand cmd = new SqlCommand("insert into tbl values ('" + textBox1.Text + "', '" + textBox2.Text + "')", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            else
            {
                MessageBox.Show("ERROR");
            }
        }

But it shows success even error is present

I tried to put the if statement in else

private void Validateform()
        {
            bool name = ValidateNames();
            bool number = ValidateNumbers();

            if (name && number)
            {
                MessageBox.Show("Error");
            }
            else
            {
                MessageBox.Show("SUCCESS");
                SqlCommand cmd = new SqlCommand("insert into tbl values ('" + textBox1.Text + "', '" + textBox2.Text + "')", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

It generates an error if textboxes is not valid.
But when the first textbox was fulfilled it shows success even there is an error in second textbox.

I've just noticed you are using returning true when validation fails. My bad..generally when you have a validation method it returns true if the data is valid. In essence you are asking the method "is this valid" and it returns "true" if it IS valid. Its not a hard and fast rule, but most developers use this approach.

Since your validations return false if the data is valid you need to put the Success code back inside the If block but invert your conditions:

private void Validateform()
        {
            bool name = ValidateNames();
            bool number = ValidateNumbers();

            if (!name && !number)
            {
                MessageBox.Show("SUCCESS");
                SqlCommand cmd = new SqlCommand("insert into tbl values ('" + textBox1.Text + "', '" + textBox2.Text + "')", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            else
            {
                MessageBox.Show("ERROR");
            }
        }

The "!" symbol is the NOT symbol so if(!false) is the same as if(true)...if its NOT false, then it IS true :)

Try this, or alternatively, take another look at your validation methods and see if you can rewrite your code to work with a response of true when validation succeeds.

Actually I tried

if(name==false && number==false)

but yours is much better.. thanks!

I have eight textbox that shouldn't be empty and I don't want to create eight methods..

Is there any shortcut?

instead of

private bool ValidateNames()
        {
            if (textBox1.Text == string.Empty)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

then

private bool ValidateNames()
        {
            if (textBox2.Text == string.Empty)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

You could have a single validation method, but the purpose of the code discussed above was to set error messages against indiviual controls using the ErrorProvider control so it was necessary to check each control seperately.

If you want to just check that none are empty you could place the 8 texboxes inside a panel then use a foreach loop to iterate through the panel's control collection to check them:

private void button2_Click(object sender, EventArgs e)
        {
            if (TextBoxEmpty())
                MessageBox.Show("Empty");
        }

        private bool TextBoxEmpty()
        {
            foreach (Control c in panel2.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    if ((c as TextBox).Text == "")
                        return true;
                }
            }
            return false;
        }

You could also extend the TextBoxEmpty method by passing it a panel to check:

private bool TextBoxEmpty(Panel CheckPanel)

Or even pass it a control, but then you would need to ensure that the control to be checked has a control collection :)

commented: nice +1

I see. I think i'll just go for single validation method for now..

Anyway, how to validate a checkedlistbox? It should have a check at least one.

Its your code, you can handle it anyway you like :p
I couldnt let it lie so i made a minor tweak to the method. It will now check the textboxes of a passed control and has an overloaded method that will set error text using the passed errorProvider:

private bool TextBoxEmpty(Control checkControl)
        {
            foreach (Control c in checkControl.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    if ((c as TextBox).Text == "")
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private bool TextBoxEmpty(Control checkControl, ErrorProvider error)
        {
            bool emptyFound = false;
            foreach (Control c in checkControl.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    if ((c as TextBox).Text == "")
                    {
                        emptyFound = true;
                        error.SetError(c, "Valid input required");
                    }
                    else
                    {
                        error.SetError(c, "");
                    }
                }
            }

                return emptyFound;
        }

This removes the need for handling the Validating event on each textbox. However, it does mean that the errors will only be shown when you call "TextBoxEmpty()", not when the textbox loses focus.

To check a checked list box you can use checkListBox.CheckedItems.Count to find out how many items have been checked.

commented: string.IsNullOrEmpty() method is pretty handy!!! +10
private bool ValidateAuthor()
        {
            if (checkedListBox1.CheckedItems.Count < 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

it doesn't seem to work

sorry, my mistake.. it's working.. thanks!

no problem :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.