حذف همزمان چندین رکورد GridView با استفاده از CheckBox در ASP.NET
نویسنده: عثمان رحیمی
تاریخ: ۱۳۹۳/۰۷/۰۳ ۱۳:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
CREATE TABLE [dbo].[Employee] (
[EmpId] INT NOT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (20) NOT NULL,
[City] VARCHAR (20) NOT NULL,
PRIMARY KEY CLUSTERED ([EmpId] ASC)
); <asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField> <asp:Button ID="btnDeleteRecord" runat="server" OnClick="btnDeleteRecord_Click" Text="Delete" />
function DeleteConfirm()
{
var Ans = confirm("Do you want to Delete Selected Employee Record?");
if (Ans)
{
return true;
}
else
{
return false;
}
} protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Displaying the Data
showData();
//Adding an Attribute to Server Control(i.e. btnDeleteRecord)
btnDeleteRecord.Attributes.Add("onclick", "javascript:return DeleteConfirm()");
}
} //Method for Displaying Data
protected void showData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter adapt = new SqlDataAdapter("select * from Employee",con);
con.Open();
adapt.Fill(dt);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
} protected void DeleteRecord(int empid)
{
SqlConnection con = new SqlConnection(cs);
SqlCommand com = new SqlCommand("delete from Employee where EmpId=@ID",con);
com.Parameters.AddWithValue("@ID",empid);
con.Open();
com.ExecuteNonQuery();
con.Close();
} protected void btnDeleteRecord_Click(object sender, EventArgs e)
{
foreach (GridViewRow grow in GridView1.Rows)
{
//Searching CheckBox("chkDel") in an individual row of Grid
CheckBox chkdel = (CheckBox)grow.FindControl("chkDel");
//If CheckBox is checked than delete the record with particular empid
if(chkdel.Checked)
{
int empid = Convert.ToInt32(grow.Cells[1].Text);
DeleteRecord(empid);
}
}
//Displaying the Data in GridView
showData();
} where id in (........)