c# window application

Last Reply 13 days ago By KasimA

Posted 13 days ago

Validate GridView with CheckBox (at least one checked)  in c# window application while saving the data in the database

You are viewing reply posted by: KasimA 13 days ago.
Posted 13 days ago Modified on 13 days ago

Hi ishuhasan21,

Please refer below sample.

Database

I have made use of the following table Customers with the schema as follows.

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

Namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Code

public Form1()
{
    InitializeComponent();
    this.BindGridView();
}

private void BindGridView()
{
    dgvCustomers.AllowUserToAddRows = false;
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
        {
            using (SqlDataAdapter sad = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sad.Fill(dt);
                dgvCustomers.DataSource = dt;
            }
        }
    }
    DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
    checkBoxColumn.HeaderText = "";
    checkBoxColumn.Width = 30;
    checkBoxColumn.Name = "checkBoxColumn";
    dgvCustomers.Columns.Insert(0, checkBoxColumn);
}

private void OnSubmit(object sender, EventArgs e)
{
    bool isChecked = false;
    foreach (DataGridViewRow row in dgvCustomers.Rows)
    {
        bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
        if (isSelected)
        {
            isChecked = true;
            break;
        }
    }

    lblMessage.Text = !isChecked ? "Please select at least one record." : "";
}

Screenshot