Saturday, September 18, 2010

GridView with checkbox

This article is very simple.Many time developer need to how develop Gridview with checkbox,so we can select single or multiple record to update.
Javascript file
 <script language="javascript" type="text/javascript">  
function SelectAllCheckboxes(spanChk)
{
var oItem = spanChk.children;
var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;
for(i=0;i if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
{
if(elm[i].checked!=xState)
elm[i].click();
}
}
</script>


Html code

 <form id="form1" runat="server">  
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="PersonID" />
<asp:BoundField DataField="Fname" HeaderText="Fname" SortExpression="Fname" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Delete" />
<asp:Label ID="lblmsg" runat="server" Text="Label" Visible="false"></asp:Label>
</form>


.cs code
 public partial class GridWithCheck : System.Web.UI.Page  
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnect"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
public void BindGridView()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from tbl_CustomerDetail order by CustomerID", con);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = ((CheckBox)(row.FindControl("chkSelect")));
if (cb != null && cb.Checked)
{
int custID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
string sqlstr = "delete from tbl_CustomerDetail where CustomerID='" + custID + "'";
SqlCommand mycmd;
mycmd = new SqlCommand(sqlstr, con);
con.Open();
mycmd.ExecuteNonQuery();
Page.RegisterStartupScript("pop", "&lt;script&gt;alert('Row deleted')&lt;/script&gt;");
BindGridView();
}
}
}
}

Thanks & Regards
Santosh

1 comment: