Validate fields on form before submitting data into database.
I design registration form on this form contains total 8 textboxes and 4 combobox . I want to insert these textboxes & combobox data into database by checking that textboxes & combobox values cannot be blank. Please tail me the shot code to check textboxes not to keep blank using c#.

Niravkumar VaghelaPosted Jul 25, 2012, 9:13 AM
You may try this.
Take ErrorProvider Control. And Use following code.
private void btnSave_Click(object sender, EventArgs e)
{
ErrorTracker et = new ErrorTracker(errorProvider1);
if (TextBox1.Text.Trim() == "")
{
et.SetError(TextBox1, "Required !");
}
if (TextBox2.Text.Trim() == "")
{
et.SetError(TextBox2, "Required !");
}
if (TextBox3.Text.Trim() == "")
{
et.SetError(TextBox3, "Required !");
}
if (TextBox4.Text.Trim() == "")
{
et.SetError(TextBox4, "Required !");
}
int a = et.Count;
if (!(a > 0))
{
errorProvider1.Clear();
this.SavePatientMessage();
}
}
Hope this will help you.
Sudhakar ChaudharyPosted Jul 25, 2012, 9:07 AM
private void button1_Click(object sender, EventArgs e)
{
foreach (Control cnt in this.Controls)
{
if (cnt is TextBox)
{
if (cnt.Text == "")
{
MessageBox.Show("TextBox is Blank.");
cnt.BackColor = Color.Pink;
}
}
else if (cnt is ComboBox)
{
ComboBox cmb = (ComboBox)cnt;
if (cmb.SelectedItem == null)
{
MessageBox.Show("Combox is not Selected.");
cnt.BackColor = Color.Plum;
}
}
}
}
Satyapriya NayakPosted Jul 25, 2012, 9:01 AM
It is a window or web apps.
If window then,
Try...
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;
namespace WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "" || textBox6.Text == "" || textBox7.Text == "" || textBox8.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || comboBox3.Text == "" || comboBox4.Text == "")
{
MessageBox.Show("Fields cannnot be blank");
}
else
{
MessageBox.Show("Insert");
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("a");
comboBox2.Items.Add("b");
comboBox3.Items.Add("c");
comboBox4.Items.Add("d");
}
}
}
Thanks
If this post helps you mark it as answer
kishor chourePosted Jul 25, 2012, 8:56 AM
Santhosh Kumar JayaramanPosted Jul 25, 2012, 8:44 AM
Like