【】GridView中数据的增删改查操作

时间:2024-11-15 16:52:06

前端

添加GridView控件,绑定数据源,方法参见此篇博客:/cxh6863/article/details/80441527

后端

1、添加

进行添加操作前,需添加TextBox控件来获取值,以及添加Button控件来触发Click事件

protected void btnOK_Click(object sender, EventArgs e)
    {
        //连接数据库
        // 数据库连接,用的是相对路径 数据库文件名:exam.mdb 存放于 文件夹app_data 中
        OleDbConnection myConn = new OleDbConnection();
        myConn.ConnectionString = "Provider=.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/");
        myConn.Open();
        //插入
        string strSql = "insert into Letter_Info(UserID,ReleaseTime,Context)values(" + txtUserID.Text + "," + System.DateTime.Now.ToString("yyyy-MM-dd") + "," + txtContext.Text + ")";
        OleDbDataAdapter adapt = new OleDbDataAdapter(strSql, myConn);
        DataSet ds = new DataSet();
        adapt.Fill(ds, "Letter_Info");
        myConn.Close();
        Response.Write("添加成功!");

    }

2、修改

 //更新
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = "Provider=.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/");

        conn.Open();
        string updateSql = "update Letter_Info set Context='"
            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "' where UserID='"
            + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
        OleDbDataAdapter adapt = new OleDbDataAdapter(updateSql, conn);
        DataSet ds = new DataSet();
        adapt.Fill(ds, "Letter_Info");
        conn.Close();
        GridView1.EditIndex = -1;
        // GridView1.DataBind();
        fillGridView();
    }

3、删除

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = "Provider=.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/");
        conn.Open();
        string deleteSql = "delete from Letter_Info where UserID='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
        OleDbDataAdapter adapt = new OleDbDataAdapter(deleteSql, conn);

        DataSet ds = new DataSet();
        adapt.Fill(ds, "Letter_Info");
        GridView1.DataBind();
        fillGridView();
        conn.Close();
    }

4、启动编辑和取消按钮

//编辑
 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
         = ;
        fillGridView();
    }
 //取消
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
         = -1;
        fillGridView();
    }

效果图

这里写图片描述
这里写图片描述