user2999062
user2999062

Reputation: 37

How to add TextBox validation in Windows Forms

This is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace testdb
{
     public partial class AddProject : Form
     {
           public AddProject()
           {
               InitializeComponent();
           }

          private void btn_addproject_Click(object sender, EventArgs e)
          {
              string constr = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:/Users   /Xprts_3/Documents/Database1.accdb";
              string cmdstr = "insert into tb1(name,rollno,projectdate)   (@First,@Last,@pdate)";
              OleDbConnection con = new OleDbConnection(constr);
              OleDbCommand com = new OleDbCommand(cmdstr, con);
              con.Open();
              com.Parameters.AddWithValue("@First", textBox_project_name.Text);
              com.Parameters.AddWithValue("@Last", comboBox1_project_status.Text);
              com.Parameters.AddWithValue("@pdate", dateTimePicker1.Text);
              com.ExecuteNonQuery();
              con.Close();
          }
     }
  }

I am adding data to a database on button click.

Now I want validation in it. I want an error message to appear to the user if any fields are blank, instead of inserting data into the database. How may this be achieved in Windows Forms?

Upvotes: 2

Views: 8783

Answers (9)

priyana_.net
priyana_.net

Reputation: 94

  private void btn_addproject_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(textBox_project_name.Text) && !String.IsNullOrEmpty(comboBox1_project_status.Text) && !String.IsNullOrEmpty(dateTimePicker1.Text))
    {
        string constr = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:/Users   /Xprts_3/Documents/Database1.accdb";
        string cmdstr = "insert into tb1(name,rollno,projectdate)   (@First,@Last,@pdate)";
        // 
        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand com = new OleDbCommand(cmdstr, con);
        con.Open();
        com.Parameters.AddWithValue("@First", textBox_project_name.Text);
        com.Parameters.AddWithValue("@Last", comboBox1_project_status.Text);
        com.Parameters.AddWithValue("@pdate", dateTimePicker1.Text);
        com.ExecuteNonQuery();
        con.Close();
    }
    else
    {
        lblMsg.Text="Enter data";
    }

}

Upvotes: 1

Sinatr
Sinatr

Reputation: 22008

Despite there are several answers already, I don't like either of them. Best approach (imho) would be to allow user to enter wrong data, but make it so, what he will understand himself, when he did a mistake. Usually, on the form to enter data, there will be a Label + TextBox (or some other control) for each field. Subscribe to each control OnTextChanged (OnValueChanged, etc) and check there whenever entered data are ok. If they are not, make label next to it red (or somehow else give user a hint, what data is not ok).

Additionally, just before inserting data, do a complete check of all values, with more aggressive way to inform user about his mistakes: popup window, setting focus to a control with wrong value, etc.

Point is:

  • it is good for the user to see if data is wrong immediately upon entering (to example, when entering double, then being able to see wrong decimal point character immediately will let user to quickly hit Backspace and correct it, while, if its only shown when focus is lost - additional steps are required: moving focus back, moving caret back, etc), so OnTextChanged > OnFocusLost (or Validating, Validated, etc).

  • it is bad to push user to enter specific data one by one, because he may want to enter something later, this is why doing anything aggressive (displaying popup window, setting focus back, etc) is pretty bad and annoying thing, that's why you want to do it just when user confirms his input by pressing a button Add at the end of filling the form.

  • you want to inform user what and where is wrong, so blindly checking if values are not ok and doing nothing is bad.

  • it is mostly not important to inform user, why data is wrong (because user is able to figure it out by himself), unless you have min/max checks, requiring special values, checking for bad characters, checking entered value with something else, if so - highlight both with red, or provide an additional information about error (use ErrorProvider, supply ToolTip to a label, etc). You can be lazy and only do this at the end (when pressing button), in the popup window.

And example would be:

private void textBoxName_TextChanged(object sender, EventArgs e)
{
    // name length is maximum 10
    labelName.Color = textBoxName.Text.Length > 10 ? Color.Red : SystemColors.WindowText;
}

private void buttonAddProject_Click(object sender, EventArgs e)
{
    // check name
    string name = textBoxName.Text.Trim()
    if(name.Length == 0 || name.Length > 10)
    {
        labelName.Color = Color.Red;
        textBoxName.Focus();
        textBoxName.SelectAll();
        MessageBox.Show("Name is required. Maximum length is 10.");
        return;
    }
    // check something else
    // ... if check fail - focus, messagebox, return
    // ...
    // insert data
    // ...
    DialogResult = DialogResult.Ok; // close form
}

Upvotes: 0

helgeheldre
helgeheldre

Reputation: 1101

The simples solution is to make a label on wich you inform the user when/if something has gone wrong. In your event handler you alter the text based on wether the textboxes has text or not.

For a more advanced solution you can use ErrorProvider and databinding.

    public partial class AddProject : Form
    {
        public AddProject()
        {
            InitializeComponent();
        }

        private void btn_addproject_Click(object sender, EventArgs e)
        {            
           if(string.isNullOrEmpty(textBox_project_name.Text) ||
           string.isNullOrEmpty(comboBox1_project_status.Text) ||
           string.isNullOrEmpty(dateTimePicker1.Text))
          {  
              errorLabel.Text = "Enter text in all fields";
              return;
          } 
          else
          {
              errorLabel.Text = "";                 
          }

          string constr = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:/Users   /Xprts_3/Documents/Database1.accdb";
          string cmdstr = "insert into tb1(name,rollno,projectdate)   (@First,@Last,@pdate)";

          OleDbConnection con = new OleDbConnection(constr);
          OleDbCommand com = new OleDbCommand(cmdstr, con);
          con.Open();

          com.Parameters.AddWithValue("@First", textBox_project_name.Text);
          com.Parameters.AddWithValue("@Last", comboBox1_project_status.Text);
          com.Parameters.AddWithValue("@pdate", dateTimePicker1.Text);
          com.ExecuteNonQuery();
          con.Close();        
       }
}

Upvotes: 0

Ramashankar
Ramashankar

Reputation: 1658

You can validate the value of text box before doing db operation.

private void btn_addproject_Click(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(textBox_project_name.Text) && !String.IsNullOrEmpty(comboBox1_project_status.Text) && !String.IsNullOrEmpty(dateTimePicker1.Text))
    {

        MessageBox.Show("Enter data");
        return;
    }        

    string constr = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:/Users   /Xprts_3/Documents/Database1.accdb";
    string cmdstr = "insert into tb1(name,rollno,projectdate)   (@First,@Last,@pdate)";

    OleDbConnection con = new OleDbConnection(constr);
    OleDbCommand com = new OleDbCommand(cmdstr, con);
    con.Open();
    com.Parameters.AddWithValue("@First", textBox_project_name.Text);
    com.Parameters.AddWithValue("@Last", comboBox1_project_status.Text);
    com.Parameters.AddWithValue("@pdate", dateTimePicker1.Text);
    com.ExecuteNonQuery();
    con.Close();


}

Upvotes: 0

Vishal Patel
Vishal Patel

Reputation: 973

You can validate text entries by adding below lines of code in your button click event....

if (String.IsNullOrEmpty(textBox_project_name.Text))
    {
        Response.Write("<script>alert('Enter project name.')</script>");
    }

    if (String.IsNullOrEmpty(comboBox1_project_status.Text))
    {
        Response.Write("<script>alert('Enter project status.')</script>");
    }

    if (string.IsNullOrEmpty(dateTimePicker1.text))
    {
        Response.Write("<script>alert('Select Proper Date.')</script>");
    }

Upvotes: 0

Tan
Tan

Reputation: 2178

Hi you have to check with if statements if textBox_project_name.Text, comboBox1_project_status.Text and dateTimePicker1.Text is not null or empty.

This is one way to do it.

private void btn_addproject_Click(object sender, EventArgs e)
    {
        if(string.IsNullOrEmpty(textBox_project_name.Text) || 
        string.IsNullOrEmpty(comboBox1_project_status.Text) || 
        string.IsNullOrEmpty(dateTimePicker1.Text)){
            //Display your error 
                     return;
        }


        string constr = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:/Users   /Xprts_3/Documents/Database1.accdb";
        string cmdstr = "insert into tb1(name,rollno,projectdate)   (@First,@Last,@pdate)";
     // 
       OleDbConnection con = new OleDbConnection(constr);
       OleDbCommand com = new OleDbCommand(cmdstr, con);
       con.Open();
       com.Parameters.AddWithValue("@First", textBox_project_name.Text);
       com.Parameters.AddWithValue("@Last", comboBox1_project_status.Text);
       com.Parameters.AddWithValue("@pdate", dateTimePicker1.Text);
         com.ExecuteNonQuery();
        con.Close();


     }

Upvotes: 0

coder
coder

Reputation: 13248

First, you need to obtain all the text boxes in form of a sequence, for instance like this:

var boxes = Controls.OfType<TextBox>();

Then, you can iterate over them, and set the error accordingly:

foreach (var box in boxes)
{
    if (string.IsNullOrWhiteSpace(box.Text))
    {
        errorProvider1.SetError(box, "Please fill the required field");
    }
}

Upvotes: 0

chris_techno25
chris_techno25

Reputation: 2487

I usually subscribe to the LostFocus event of textboxes, this way whenever the user inputs into another textbox and the current loses focus, it should prompt whatever you want. It works in my case.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Subscribe to Validating event of textBox_project_name, comboBox1_project_status, and dateTimePicker1 controls. In these handlers verify data which you have in controls and set ErrorProvider error for appropriate control if data is not valid.

E.g. validating of TextBox can look like:

void textBox_project_name_Validating(object sender, CancelEventArgs e)
{
    if (String.IsNullOrEmpty(textBox_project_name.Text))
    {
       e.Cancel = true;
       errorProvider1.SetError(textBox_project_name, "Required");   
    }
    else
    {
       errorProvider1.SetError(textBox_project_name, "");  
    }
}

Upvotes: 1

Related Questions