日期:2014-05-17  浏览次数:20396 次

在gridview分页中删除数据
HTML code
<ItemTemplate>
                        <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Del"
                            Text="删除" OnClientClick="return confirm('确定删除吗?')" CommandArgument='<%# Container.DataItemIndex %>'/>                                                                                   
                    </ItemTemplate>


C# code
    protected void gv_User_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            int iIndex = Convert.ToInt16(e.CommandArgument);
            Response.Write(iIndex);
            string deletStuId = gv_User.DataKeys[iIndex].Value.ToString();
            Response.Write(string.Format("您要删除的stuID为{0},您要删除的行是{1}", gv_User.DataKeys[iIndex].Value, iIndex + 1));
            string connString = "server=(local);database=db_02;integrated security=sspi;";
            string sSql = "Delete from tb_student where stuId=@stuId";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sSql, conn))
                {
                    cmd.Parameters.Add("@stuId", deletStuId);
                    ClientScript.RegisterStartupScript(Page.GetType(), "", string.Format("<script>alert('删除{0}条记录');</script>", cmd.ExecuteNonQuery()));
                    setBind();
                }
            }
        }
    }

为什么在分页中点删除后,得到的行的索引是没分页前的,假如原先是12行,但在分后,在第6中显示,应该是第2行,但CommandArgument却是12,
所以删除出错,这应该怎么解决呢?

------解决方案--------------------
CommandArgument跟主键ID绑定
------解决方案--------------------
CommandArgument 绑定你的stuId
CommandArgument='<%# Eval("stuId") %>'
------解决方案--------------------
CommandArgument='<%# Container.DataItemIndex %>'/> 
直接把这个该成绑定主键的值
后台就可以直接获取ID值
string id = e.CommandArgument.ToString(); //主键
,删除就简单了,你说呢.
------解决方案--------------------
可以把绑定放在RowDataBound事件中
C# code

if(e.Row.RowType == DataControlRowType.DataRow)
{
   Button btn = e.Row.FindControl("Button1") as Button; 
   if(btn != null)
   {
      btn.CommandArgument = e.Row.RowIndex;
   }
}