Reputation: 1508
I have a requirement where I want to delete multiple row by placing check-box in each row I want to place only single button for deleting multiple row in a gridview....
I am using this code but it is not working ...
EmployeeModel.EmployeeEntities obj=new EmployeeModel.EmployeeEntities();
foreach(GridViewRow row in grdVw.Rows)
{
if ((row.FindControl("chkBox1") as CheckBox).Checked)
{
string id=grdVw.DataKeys[row.RowIndex].Value.ToString();
int a=int.Parse(id);
var result = from n in obj.Emps where n.Ecode == a select n;
obj.DeleteObject(result.First());
}
}
obj.SaveChanges();
Here is the code for declaring my GridView
:
<asp:GridView ID="grdVw" runat="server" AutoGenerateColumns="false" ToolTip="Employee Details" DataKeyNames="Ecode">
<Columns>
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="chkBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="EmpCode" DataField="Ecode" />
<asp:BoundField HeaderText="EmpName" DataField="Ename" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="City" DataField="city" />
<asp:BoundField HeaderText="EmailId" DataField="Email" />
<asp:BoundField HeaderText="DOB" DataField="DOB" />
<asp:BoundField HeaderText="JoinDate" DataField="joinDate" />
<asp:BoundField HeaderText="Salary" DataField="Salary" />
</Columns>
</asp:GridView>
Upvotes: 1
Views: 2188
Reputation: 34834
Your if ((row.FindControl("chkBox1") as CheckBox).Checked)
condition is not true the first time though, because you are encountering the header row of your GridView
in the first iteration of the loop through all of the rows in the grid, like this:
foreach(GridViewRow row in grdVw.Rows)
You need to check the row type, like this:
EmployeeModel.EmployeeEntities obj=new EmployeeModel.EmployeeEntities();
foreach(GridViewRow row in grdVw.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
if ((row.FindControl("chkBox1") as CheckBox).Checked)
{
string id=grdVw.DataKeys[row.RowIndex].Value.ToString();
int a=int.Parse(id);
var result = from n in obj.Emps where n.Ecode == a select n;
obj.DeleteObject(result.First());
}
}
}
obj.SaveChanges();
Note: Please read the MSDN documentation for GridViewRow.RowType Property for more information about the different types of rows in the GridView
.
UPDATE:
Try binding your GridView
only on non-postbacks (read: first time the page loads), like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Blcommon obj = new Blcommon();
grdVw.DataSource = obj.GetEmployee();
grdVw.DataBind();
}
}
Upvotes: 2
Reputation: 6839
You have to specify which cell contains the checkbox. Change the code for:
row.Cells[/*index of the cell*/].FindControl("chkBox1")
Upvotes: 2