【发布时间】:2016-10-19 18:05:17
【问题描述】:
我有以下 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
【问题讨论】:
-
两个查询都包含语法错误。奇怪的是你没有看到任何异常。您是否在不显示异常的情况下捕获异常?顺便问一下,GetData 的代码在哪里?这里似乎很重要
-
命令文本查询字符串看起来不对,使用try catch查看字符串错在哪里。
-
@Steve 抱歉,更新了代码。我希望我知道你在说什么......谢谢你的帮助:-)