In this article I will explain how to save (insert) CheckBox value to SQL Server database in ASP.Net using C# and VB.Net.
The value will be saved to SQL Server database depending on whether CheckBox is checked or unchecked on Button click in ASP.Net.
Database
I have made use of the following table Employees with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of a TextBox, a CheckBox and a Button.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server" />
</td>
</tr>
<tr>
<td>
Ready to relocate:
</td>
<td>
<asp:CheckBox ID="chkRelocate" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
</td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Save (Insert) CheckBox value to Database in ASP.Net
Inside the Submit Button click event handler, the value of Name TextBox is fetched and saved in a variable and then based on whether the CheckBox is checked or unchecked, the value of Relocate variable is set as Y or N respectively.
Finally the Name and Relocate values is inserted into the SQL Server Database table.
C#
protected void Submit(object sender, EventArgs e)
{
string name = txtName.Text.Trim();
string relocate = chkRelocate.Checked ? "Y" : "N";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Name, Relocate) VALUES(@Name, @Relocate)"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Relocate", relocate);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim name As String = txtName.Text.Trim()
Dim relocate As String = If(chkRelocate.Checked, "Y", "N")
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO Employees(Name, Relocate) VALUES(@Name, @Relocate)")
cmd.Connection = con
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Relocate", relocate)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Screenshots
Page with TextBox and CheckBox
The values saved in database table
Downloads