我有以下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
答案 0 :(得分:0)
正如我从上面的代码中看到的那样,您在两个查询中都存在语法错误,但最重要的是您没有将命令与连接相关联。因此,除非在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方法中创建了连接,因此您不需要在两种调用方法中使用它。