Wednesday, December 21, 2011

Checkbox in grid view in asp.net||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 asp.net.Grid 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="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<gridview autogeneratecolumns="False" id="gvOrdr" runat="server">
<columns>
<templatefield>
<itemtemplate>
<checkbox id="chkOrdr" runat="server"></checkbox>
</itemtemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkMainheadr"
OnCheckedChanged="chkMainheadr_OnCheckedChanged"
AutoPostBack="true" runat="server" />
</HeaderTemplate>

</templatefield>

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

</columns>
</gridview></div></form>
</body>
</html>

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;
}
}
else
{
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");
    if(chsubmit.Checked)
    s=s+gvemp.Rows[i].cells[2].Text+;

  }
//place s variable in to context
  context.items.Add("sps",s);
 

No comments:

Bel