MultiDeleting using CheckBox in ItemTemplate and DeleteButton outside GridView
In ASPX:
<table><tr><td align=”left”><asp:Button ID=”btnDelete” runat=”server” Text=”Delete” OnClick=”btnDelete_Click” /> </td>
</tr><tr><td><asp:GridView ID=”gvwCountries” runat=”server”
AutoGenerateColumns=”false”DataKeyNames=”countryID” ><Columns><asp:TemplateField>
<ItemTemplate><asp:CheckBox ID=”chkCountries” runat=”server” /></ItemTemplate></asp:TemplateField>
<asp:TemplateField><ItemTemplate><asp:Label ID=”lblCountries” runat=”server” Text=’<%# Bind(“countryName”) %>‘></asp:Label>
<input id=”hdnCountryID” type=”hidden” runat=”server” value=’<%# Bind(“countryID”) %>‘ /></ItemTemplate></asp:TemplateField></Columns>
</asp:GridView></td></tr> </table>In ASPX.CS:
string strConn = String.Empty;SqlConnection sqlConn;SqlCommand cmdCountries;SqlDataAdapter adapCountries;DataSet dsCountries = new DataSet();SqlParameter parmCountries = new SqlParameter();protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)BindGrid();}protected void btnDelete_Click(object sender, EventArgs e){bool blnFlag = false;string cScript;
foreach (GridViewRow gvr in gvwCountries.Rows){bool blnIsChecked = ((CheckBox)gvr.FindControl(“chkCountries”)).Checked;int intCountryID = Convert.ToInt32(((HtmlInputHidden)gvr.FindControl(“hdnCountryID”)).Value);if (blnIsChecked){parmCountries = new SqlParameter(“@CountryID”, intCountryID);bool mybln = ExcecuteNonquery(“SP_DeleteCountries”, parmCountries);blnFlag =
true;}}if (!blnFlag){cScript = “<script>alert(‘Please Select atleast one CheckBox’);</script>”;ClientScript.RegisterStartupScript(typeof(Page), “clientscript”, cScript);}BindGrid();}
protected void BindGrid(){strConn = ConfigurationManager.ConnectionStrings["LoginCon"].ToString();sqlConn = new SqlConnection(strConn);cmdCountries =
new SqlCommand(“Select * from tbl_countries”, sqlConn);adapCountries = new SqlDataAdapter(cmdCountries);adapCountries.Fill(dsCountries);gvwCountries.DataSource = dsCountries;gvwCountries.DataBind();
}
protected bool ExcecuteNonquery(string strSql, SqlParameter sqlParm){SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginCon"].ToString());SqlCommand cmd;try{sqlConn.Open();cmd =
new SqlCommand(strSql);cmd.Connection = sqlConn;cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add(sqlParm);cmd.ExecuteNonQuery();if (cmd != null) cmd.Dispose();sqlConn.Close();
return true;}catch (Exception ex){return false;}}The SP:
CREATE PROCEDURE dbo.SP_DeleteCountries(@CountryID int
)ASBEGIN DELETE FROM [tbl_Countries] where [countryID] = @CountryIDEND
Posted by naveenj