为什么不'我的简单c#网站更新数据库使用GridView

本文关键字:数据库 更新 GridView 网站 我的 简单 为什么不 | 更新日期: 2023-09-27 18:13:54

我有以下c#更新记录,但是文本框显示,但不更新到数据库。同样,我也不能添加记录。

 private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }

添加:

protected void AddNewMainPost(object sender, EventArgs e)
{
    string postID = ((TextBox)GridView1.FooterRow.FindControl("txtPostID")).Text; 
    string Name = ((TextBox)GridView1.FooterRow.FindControl("txtSelect")).Text;
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
    "values(@postID, @selectionText,);" +
     "select postID,selectionText, from homepageSelection";
    cmd.Parameters.Add("@postID", SqlDbType.VarChar).Value = postID;
    cmd.Parameters.Add("@selectionText", SqlDbType.VarChar).Value = Name;
    GridView1.DataSource = GetData(cmd);
    GridView1.DataBind(); 
}

   protected void UpdateMainPost(object sender, GridViewUpdateEventArgs e)
    {
        string postID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblpostID")).Text;
        string Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSelec")).Text;
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "update homepageSelection set selectionText=@selectionText, " +
         "where postID=@postID;" +
         "select postID,selectionText from homepageSelection";
        cmd.Parameters.Add("@postID", SqlDbType.VarChar).Value = postID;
        cmd.Parameters.Add("@selectionText", SqlDbType.VarChar).Value = Name;
        GridView1.EditIndex = -1;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind(); 
    }

我在数据库中有两个字段:

Table: homepageSelection Fields: postID and selectionText

为什么不'我的简单c#网站更新数据库使用GridView

从上面的代码中可以看出,两个查询都有语法错误,但最重要的是没有将命令与连接关联。因此,除非您在GetData方法中重新创建连接,否则您的命令将无法执行。

所以,要修复语法错误

"select postID,selectionText from homepageSelection";
                           ^^^ comma not valid here
cmd.CommandText = @"update homepageSelection set 
                    selectionText=@selectionText" +
                                               ^^^^  again comma not valid here
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
                  "values(@postID, @selectionText);" +
                                                 ^^^ no comma here

编辑:似乎您在GetData方法中创建了连接,因此您不需要在两个调用方法中创建连接。