In this article I will explain with an example, how to insert (save) selected (checked) rows from DataGridView to Database in Windows Forms (WinForms) Application using C# and VB.Net.
When the Insert button is clicked, a loop will be executed and all the rows of DataGridView for which the CheckBox is checked (selected) will be inserted into Database in Windows Forms (WinForms) Application using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Form Controls
The below Form consists of a DataGridView control and a Button.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Populating DataGridView
Inside the Form Load event, the DataGridView is populated with a dynamic DataTable with some dummy records.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.BindDataGridView();
}
private void BindDataGridView()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
this.dataGridView1.DataSource = dt;
//Add a CheckBox Column to the DataGridView at the first position.
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 30;
checkBoxColumn.Name = "checkBoxColumn";
dataGridView1.Columns.Insert(0, checkBoxColumn);
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BindDataGridView()
End Sub
Private Sub BindDataGridView()
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
Me.dataGridView1.DataSource = dt
'Add a CheckBox Column to the DataGridView at the first position.
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = ""
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
dataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
Insert (Save) Selected (Checked) rows from DataGridView to Database
When the Insert Button is clicked, a loop is executed over the DataGridView rows. Inside the loop, a check is performed whether the CheckBox is checked (selected) or not.
If the CheckBox is checked (selected), the values from each column (cell) of the DataGridView is fetched and the record is inserted into the database table.
Finally the count of the total inserted records is displayed using MessageBox.
C#
private void btnInsert_Click(object sender, EventArgs e)
{
int inserted = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
if (isSelected)
{
string constring = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@CustomerId, @Name, @Country)", con))
{
cmd.Parameters.AddWithValue("@CustomerId", row.Cells["Id"].Value);
cmd.Parameters.AddWithValue("@Name", row.Cells["Name"].Value);
cmd.Parameters.AddWithValue("@Country", row.Cells["Country"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
inserted++;
}
}
if (inserted > 0)
{
MessageBox.Show(string.Format("{0} records inserted.", inserted), "Message");
}
}
VB.Net
Private Sub btnInsert_Click(sender As System.Object, e As System.EventArgs) Handles btnInsert.Click
Dim inserted As Integer = 0
For Each row As DataGridViewRow In dataGridView1.Rows
Dim isSelected As Boolean = Convert.ToBoolean(row.Cells("checkBoxColumn").Value)
If isSelected Then
Dim constring As String = "Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("INSERT INTO Customers VALUES(@CustomerId, @Name, @Country)", con)
cmd.Parameters.AddWithValue("@CustomerId", row.Cells("Id").Value)
cmd.Parameters.AddWithValue("@Name", row.Cells("Name").Value)
cmd.Parameters.AddWithValue("@Country", row.Cells("Country").Value)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
inserted = inserted + 1
End If
Next
If inserted > 0 Then
MessageBox.Show(String.Format("{0} records inserted.", inserted), "Message")
End If
End Sub
Screenshots
Downloads