Wednesday, December 21, 2011

Checkbox in grid view in||Check/Uncheck all check boxes in gridview

In previous articles i explained delete multiple rows in gridview using checkbox,Export Gridview Excel ,Export Gridview Data to PDF document,Export gridview to Word in view is providing different types of field for customization such as bound field,check box,image field,Hyperlink,Command,Template fields.Bound field is the default field for grid view.Here i will show how to use the check box inside grid view and add the value of selected row into Context.

<html xmlns="">
<head runat="server">
<form id="form1" runat="server">
<gridview autogeneratecolumns="False" id="gvOrdr" runat="server">
<checkbox id="chkOrdr" runat="server"></checkbox>
<asp:CheckBox ID="chkMainheadr"
AutoPostBack="true" runat="server" />


<boundfield datafield="UserID" headertext="User ID">
<boundfield datafield="UserName" headertext="User Name">
<boundfield datafield="Role" headertext="Role">


Code behind:
In grid view Find Control method is provided which is access web server control with in the Template field.This return Obj type,it should be Type casted to Check Box type.So that property can be accessed.Here we will checked one check box then the value of particular row in to string using on OnCheckedChanged event
Note:We can add that string value to Text property controls like Text box,Label etc
Checked &unchecked All:
Here i have one check box in header template in aspx page.if check the header check box then all the check box should be checked .if unchecked the header check box then all the check box should be unchecked

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class CheckAllGridview : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected void chkMainheadr_CheckedChanged(object sender, EventArgs e)
checkBox chkall =(CheckBox)Gvemp.HeaderRow.FindControl("chkMainheadr");
if (chkMainheadr.Checked == true)
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
CheckBox chkIndividual =(CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = true;
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
CheckBox chkIndividual = (CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = false;
Get the Selected CheckBox value in Gridview:
public void chk_OnCheckedChanged(object sender, EventArgs e)
    string s;
    CheckBox chsubmit=(CheckBox)Gvemp.Rows[i].FindControl("chkOrdr");

//place s variable in to context

No comments: