How To Add Checkbox In Gridview In C# Windows Application
In this article I will explain with an example, how to populate (bind) CheckBox in GridView from database in ASP.Net using C# and VB.Net.
This article besides explains how to relieve the CheckBox checked (selected) values to database in ASP.Internet using C# and VB.Cyberspace.
Database
I have made employ of the following table Hobbies with the schema as follows.
I accept already inserted few records in the table.
Note : Yous can download the database table SQL past clicking the download link below.
HTML Markup
The following HTML Markup consists of an ASP.Cyberspace GridView with a TemplateField and one BoundField cavalcade.
The TemplateField cavalcade consists of a CheckBox. The Checked property of the CheckBox is jump to the IsSelected column which is of Chip data type and hence when the value saved is True the CheckBox will exist selected and vice versa.
Beneath the GridView, there is a Button for saving checked (selected) CheckBox values to database.
The DateKeyNames property has been set up for GridView to store the Chief Key which will be afterwards used to update the records in database.
< asp : GridView ID ="GridView1" runat ="server" AutoGenerateColumns ="faux" DataKeyNames ="HobbyId">
< Columns >
< asp : TemplateField >
< ItemTemplate >
< asp : CheckBox ID ="chkSelect" runat ="server" Checked =' <% # Eval("IsSelected") %> ' />
</ ItemTemplate >
</ asp : TemplateField >
< asp : BoundField DataField ="Description" HeaderText ="Hobby" ItemStyle-Width ="150px" />
</ Columns >
</ asp : GridView >
< br />
< asp : Push button ID ="btnSave" runat ="server" Text ="Save" OnClick ="Save" />
Namespaces
Yous will need to import the following namespaces.
C#
using System.Information;
using Organization.Configuration;
using System.Data.SqlClient;
VB.Cyberspace
Imports Arrangement.Data
Imports Organisation.Configuration
Imports System.Data.SqlClient
Binding the GridView
Inside the Page Load event handler, the GridView is populated with the records from the Hobbies table.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
individual void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Description], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender Every bit Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Individual Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT [HobbyId], [Description], [IsSelected] FROM Hobbies")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill up(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Stop Using
End Using
End Using
End Using
End Sub
Updating the CheckBox values to Database
When the Save Push button is clicked, a loop is executed over the GridView rows and then the HobbyId from the DataKeys and the CheckBox values are fetched.
The fetched values are used to update the record in the database table.
Finally, the page is redirected to itself to refresh the GridView with the updated values.
C#
protected void Save(object sender, EventArgs eastward)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE Hobbies Fix [IsSelected] = @IsSelected WHERE HobbyId=@HobbyId";
cmd.Connection = con;
con.Open();
foreach (GridViewRow row in GridView1.Rows)
{
//Get the HobbyId from the DataKey property.
int hobbyId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
//Become the checked value of the CheckBox.
bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;
//Relieve to database.
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@HobbyId", hobbyId);
cmd.Parameters.AddWithValue("@IsSelected", isSelected);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
VB.Cyberspace
Protected Sub Save(sender As Object, e As EventArgs)
Dim constr As Cord = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con Every bit New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "UPDATE Hobbies SET [IsSelected] = @IsSelected WHERE HobbyId=@HobbyId"
cmd.Connection = con
con.Open()
For Each row As GridViewRow In GridView1.Rows
'Go the HobbyId from the DataKey property.
Dim hobbyId As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Values(0))
'Become the checked value of the CheckBox.
Dim isSelected As Boolean = TryCast(row.FindControl("chkSelect"), CheckBox).Checked
'Relieve to database.
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("@HobbyId", hobbyId)
cmd.Parameters.AddWithValue("@IsSelected", isSelected)
cmd.ExecuteNonQuery()
Next
con.Close()
Response.Redirect(Asking.Url.AbsoluteUri)
End Using
End Using
Finish Sub
Screenshot
Demo
Downloads
Source: https://www.aspsnippets.com/Articles/Populate-bind-CheckBox-in-GridView-from-database-in-ASPNet-using-C-and-VBNet.aspx
Posted by: gomezarefling.blogspot.com
0 Response to "How To Add Checkbox In Gridview In C# Windows Application"
Post a Comment