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

前端

添加GridView控件,绑定数据源,方法参见此篇博客:https://blog.csdn.net/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=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/Database.mdb");
        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=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/Database.mdb");

        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=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/Database.mdb");
        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)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillGridView();
    }
 //取消
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillGridView();
    }

效果图

【ASP.NET】GridView中数据的增删改查操作_第1张图片
【ASP.NET】GridView中数据的增删改查操作_第2张图片

你可能感兴趣的:(#,ASP.NET,#,GridView)