1

我有一个要求,我想通过在每一行中放置复选框来删除多行我只想放置一个按钮来删除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(); 

这是声明 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>
4

2 回答 2

2

您必须指定哪个单元格包含复选框。更改以下代码:

row.Cells[/*index of the cell*/].FindControl("chkBox1")
于 2013-08-01T13:46:08.937 回答
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(); 

注意:请阅读GridViewRow.RowType 属性的 MSDN 文档,了解有关GridView.

更新:

尝试将您的唯一绑定GridView在非回发(阅读:页面首次加载时),如下所示:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack)
    {
        Blcommon obj = new Blcommon(); 
        grdVw.DataSource = obj.GetEmployee(); 
        grdVw.DataBind();
    } 
}
于 2013-08-01T14:07:13.620 回答