欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GridView 编辑,更新,删除 等操作

程序员文章站 2022-03-09 10:37:54
...

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bindgrid();
}//编辑按键下的取消代码。将EditIndex=-1,然后在绑定数据库。

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
         string id = GridView1.DataKeys[e.RowIndex][0].ToString();
         DeleteGridView(id);
         Bindgrid();
    }// id = GridView1.DataKeys[e.RowIndex][0].ToString();获得girdwiew中表的主键,作为删除数据的标识。DeleteGirdView()为自己写的删除函数


    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        Bindgrid();
    }//获取当前编辑状态

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string id = GridView1.DataKeys[e.RowIndex][0].ToString();
        string uid = ((TextBox )GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        string upassword = ((TextBox )GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        string upower = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
        UpdataGridView(id, uid, upassword, upower);
        GridView1.EditIndex = -1;
        Bindgrid();

    }//获得GridView中选中行的各列数据,用UpdataGridView()更新数据

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        Bindgrid();
    }//换页的时候获取当前编辑页
   

    public void UpdataGridView(string id,string uid,string upassword,string upower)
    {
       SqlConnection con=new SqlConnection ("server=localhost;database=YGXXXT;uid=sa;password=00");
       string sql="update Users set ID='"+id+"',UID='"+uid+"',UPassword='"+upassword+"',UPower='"+upower+"'";
       SqlCommand cmd=new SqlCommand (sql,con );
       con.Open ();
       cmd.ExecuteNonQuery ();
       con.Close();
       
    }//更新数据库数据,注意sql语句里的'"+id+'"不要弄错格式~~~
    public void DeleteGridView(string id)
    {
        SqlConnection con = new SqlConnection("server=localhost;database=YGXXXT;uid=sa;password=00");
        string sql = "delete Users where ID='"+id +"'";
        SqlCommand cmd = new SqlCommand(sql, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }//删除数据库数据
相关标签: Asp asp.net