gridview-----添加OnRowDeleting事件及确认事件OnRowCreated

来源:互联网 发布:mac应用软件 编辑:程序博客网 时间:2024/06/06 03:38

 

注意 :事件的参数类型如GridViewDeleteEventArgs 、GridViewRowEventArgs;把数据库链接和表名做适当的处理.
前台:OnRowDeleting ="GridView1_OnRowDeleting"  OnRowCreated="GridView1_RowCreated"
后台:
 protected void GridView1_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32  ( GridView1.DataKeys[e.RowIndex].Value);//获得要删除行的id
        //数据库操作,最好用存储过程
        string DeleteCommand;
        DeleteCommand = "delete 表名 where SDBP_MID='" +id +"'";
        GridViewBind(DeleteCommand , "表名");
        //重新绑定gridview       
        string  sqlstr = "select * from 表名";
        GridViewBind(sqlstr, "表名");
    } 
 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)//添加确认事件,此在绑定datasource时也可用
    {
        if (e.Row != null && e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lb = e.Row.Cells[5].Controls[0] as LinkButton;//Cell[]中应该是你的删除列的列数-1

            //如果是Button按钮,即 ButtonType="Button" 时
            //则 Button lb = e.Row.Cells[5].Controls[0] as Button;

            lb.Attributes.Add("onclick", "return window.confirm('确认要删除该记录吗?')");

        }
    }
    protected void GridViewBind(string sqlstr, string tablename)//根据tablename和sql语句绑定数据库
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings

["tahx2006ConnectionString"].ConnectionString);
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
        DataSet ds = new DataSet();
        da.Fill(ds, tablename );
        GridView1.DataSource = ds.Tables[tablename ].DefaultView;
        GridView1.DataBind();
    }
 

原创粉丝点击