Friday, April 4, 2008

Delete Checked in Gridview

First thing create Database (Company) with Table (Employee)
which has fields (Id,Name)

Second enter data in Database

Now create new website

in Default.aspx

write the following javascript code

//function SelectAll(id)
// {
// var frm = document.forms[0];
//
// for (i=0;i < frm.elements.length;i++)
// {
// if (frm.elements[i].type == "checkbox")
// {
// frm.elements[i].checked = document.getElementById(id).checked;
//
// }
// }
//
// }

and add Gridview and button (Delete)and lable (lblMsg)
and in Gridview add Template field and In HeaderTemplate add checkbox (cbxAll) and in ItemTemplate checkbox (cbxId)

and in Default.aspx.cs

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
//adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbxAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbxAll")).ClientID + "')");
}
}

protected void btn_Delete_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbxId");

if (checkbox.Checked == true)
{
// method to delete by Id

lblMsg.Text = "Selected deleted";
GridView1.DataBind();


}

}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
}
}

No comments: