Pages

Saturday 13 April 2013

How to check all CheckBox in GridView in asp.net C#

DATABASE SCRIPT
  • Create a database and name to db_gridview_chkbox and copy paste the following script into your sql sever.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_messages](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[to_subject] [varchar](500) NULL,
[from] [varchar](12) NULL,
[date] [datetime] NULL CONSTRAINT [DF_tbl_messages_date]  DEFAULT (getdate())
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

SOURCE CODE
  • Now add a new page and name it Default.aspx and copy paste the following source code in it.

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Untitled Page</title>
<script type = “text/javascript”>
<!–
function Checkbox_Click(obj)
{
// get the Row based on checkbox
var Row = obj.parentNode.parentNode;
// get the reference of GrdView
var GrdView = Row.parentNode;
//get all input elements in GrdView
var Input_List = GrdView.getElementsByTagName(“input”);
for (var i=0;i<Input_List.length;i++)
{
//first element is the Header_CheckBox
var Header_CheckBox = Input_List[0];
// checkboxes are checked check/uncheck Header_CheckBox.
var Checked = true;
if(Input_List[i].type == “checkbox” && Input_List[i] != Header_CheckBox)
{
if(!Input_List[i].checked)
{
Checked = false;
break;
}
}
}
Header_CheckBox.checked = Checked;
}
function Checked_All(obj)
{
var GrdView = obj.parentNode.parentNode.parentNode;
var Input_List = GrdView.getElementsByTagName(“input”);
for (var i=0;i<Input_List.length;i++)
{
var Row = Input_List[i].parentNode.parentNode;
if(Input_List[i].type == “checkbox”  && obj != Input_List[i])
{
if (obj.checked)
{
Input_List[i].checked=true;
}
else
{
Input_List[i].checked=false;
}
}
}
}
//–>
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”Gridview_Checkbox” runat=”server”  AutoGenerateColumns = “False” style=”float:none”
AllowPaging =”True”  onpageindexchanging=”Gridview_checkbox_PageIndexChanging”
CellPadding=”4″ ForeColor=”#333333″ GridLines=”None” ShowFooter=”True”
Width=”388px”>
<FooterStyle BackColor=”#990000″ Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#FFFBD6″ ForeColor=”#333333″ />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID=”check_All” runat=”server”  onclick = “Checked_All(this);” /> <!– on click passin value to Checked_All() —>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”check_box” runat=”server” onclick = “Checkbox_Click(this)” /><!– on click passin value to Checkbox_Click() —>
<asp:Label ID=”lbl_id” runat=”server” Text=’<%#Eval(“id”) %>’ Visible=”false” ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”From”>
<ItemTemplate>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(“from”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Subject”>
<ItemTemplate>
<%#  GetBoldString(Eval(“to_subject”))%> <!– defined a public method in code-behind –>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Date”>
<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(“Date”,”{0:dd MMM yyyy}”)%>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor=”#FFCC66″ ForeColor=”#333333″ HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#FFCC66″ Font-Bold=”True” ForeColor=”Navy” />
<HeaderStyle  HorizontalAlign=”Left” BackColor=”#990000″ Font-Bold=”True”
ForeColor=”White” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>
<asp:LinkButton ID=”lnk_bottomInbox_delete” runat=”server”  onclick=”lnk_bottomInbox_delete_Click”>Delete</asp:LinkButton>
<br />
<asp:Label ID=”lbl_msg” runat=”server” ForeColor=”Red”></asp:Label>

</div>
</form>
</body> </html>

A Design View.

CODE
  • Now copy and paste the Code in you code-behind file.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
SqlDataAdapter adp;
SqlCommand cmd;
DataTable dt;
SqlConnection con = new SqlConnection();
int count_selected_records;  // will count the total selected rows.
Label selected_row_id; // will tell the which record (checkbox) selected.
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
con.Open();
if (con.State == ConnectionState.Closed)
{        con.Open();     }
con.Close();
if (IsPostBack == false)
{
// will call the method and bind the GridView.
grdview_data();
}
}

private void grdview_data()
{
if (con.State == ConnectionState.Closed)
{ con.Open(); }
adp = new SqlDataAdapter(@”Select *  from tbl_messages order by id DESC”, con);
dt = new DataTable();
adp.Fill(dt);
adp.Dispose();
if (dt.Rows.Count == 0)
{
lbl_msg.Text = “No Record found”;
Gridview_Checkbox.DataSource = dt;
Gridview_Checkbox.DataBind();
}
else
{
lbl_msg.Text = String.Empty;
Gridview_Checkbox.DataSource = dt;
// binding the gridView.
Gridview_Checkbox.DataBind();
}
dt.Dispose();
con.Close();
}

// The following method  defined in source code under GridView
// where he will pass the string and the code will make the subject text BOLD.
public string GetBoldString(object _objStringToBold) // passing the to_subject col. value.
{
string _StringToBold = Convert.ToString(_objStringToBold);
return “<strong>” + _StringToBold + “</strong>”; // returning the value.
}
// will check which checkbox is selected and after that will perfom the action on it.
private void Selected_items()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}

// find the checkbox name ‘check_All’ in gridview
CheckBox chkAll = (CheckBox)Gridview_Checkbox.HeaderRow.Cells[0].FindControl(“check_All”);
chkAll.Checked = true;
count_selected_records = 0;
for (int j = 0; j <= Gridview_Checkbox.Rows.Count – 1; j++)
{
// find  the selected checkbox name ‘check_box’ in each rows.
CheckBox chk = (CheckBox)Gridview_Checkbox.Rows[j].Cells[0].FindControl(“check_box”);
if (chk.Checked == true)
{
// will check how many checkboxes are selected.
count_selected_records = count_selected_records + 1;
}    }
// it will pop up the message if there is no any checkbox selected from the Gridview.
if (count_selected_records == 0)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), “err_msg”, “alert(‘Please select at least one Message to Delete.’);”, true);
// will jump/end from the code.
return;
}

// if count_selected_records is greater than ZERO then the following code will perform.
for (int i = 0; i <= Gridview_Checkbox.Rows.Count – 1; i++)
{
// find the selected checkbox
CheckBox chk = (CheckBox)Gridview_Checkbox.Rows[i].Cells[0].FindControl(“check_box”);
if (chk.Checked == true)
{
//get the selected checkbox row id.
selected_row_id = (Label)Gridview_Checkbox.Rows[i].Cells[0].FindControl(“lbl_id”);
//pass the selected checkbox row id to Delete_Selected_items which will delete the record.
Delete_Selected_items(Convert.ToInt32(selected_row_id.Text));
}
}
grdview_data();
}

protected void Gridview_checkbox_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Gridview_Checkbox.PageIndex = e.NewPageIndex;
grdview_data();
}

// row_id will get the selected row and delete the record from database.
private void Delete_Selected_items(int row_id)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd = new SqlCommand(“delete from tbl_messages where id=@id”, con);
cmd.Parameters.AddWithValue(“@id”, row_id);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
protected void lnk_bottomInbox_delete_Click(object sender, EventArgs e)
{
try
{
Selected_items();
}
catch { }
grdview_data();
}
}


SNAPSHOTS

If not any record selected.

No comments:

Post a Comment