我有一个要求,我希望通过在每行中放置复选框来删除多行 我想只放置一个按钮来删除gridview中的多行....
我正在使用此代码,但它无效...
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();
以下是声明我的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>
答案 0 :(得分:2)
您必须指定包含复选框的单元格。 更改以下代码:
row.Cells[/*index of the cell*/].FindControl("chkBox1")
答案 1 :(得分:2)
第一次你的if ((row.FindControl("chkBox1") as CheckBox).Checked)
条件不正确,因为你在循环的第一次迭代中遇到了GridView
的标题行,通过网格中的所有行,就像这样:
foreach(GridViewRow row in grdVw.Rows)
您需要检查行类型,如下所示:
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();
注意:有关GridView
中不同类型行的详细信息,请阅读MSDN documentation for GridViewRow.RowType Property。
更新:
尝试仅在非回发时绑定GridView
(阅读:第一次加载页面),如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Blcommon obj = new Blcommon();
grdVw.DataSource = obj.GetEmployee();
grdVw.DataBind();
}
}