用C#中的更新文本框信息更新数据库
问题描述:
尝试更新学生的名字时,有一个文本框“FirstNameTextbox”信息从数据库加载到它,当我更改文本框中的信息并尝试写入更改时它只读取原始数据。因此,如果它从数据库中加载“Craig”作为第一个名字,我会编辑并在文本框中放入“Chris”,会发生什么是Craig被写入数据库而不是“Chris”用C#中的更新文本框信息更新数据库
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = @fname where stuID = @stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("@stuID", stuID);
cmd.Parameters.AddWithValue("@fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
答
你在什么时候进行实际更新?在按下按钮后,在文本框中输入值后...?您错过了处理更新的代码的方法... 也许这可能有所帮助:How to display data from database into textbox, and update it
+0
感谢Danilo ,这正是我所寻找的解决方案的类型。 #Respect –
+0
没问题的人,很高兴我能帮上忙。继续编码! –
在cmd.Parameters.AddWithValue(“@ fname”,FirstNameTextbox.Text)处设置断点。 stuID的价值是什么?你的数据库中是否有这样的条目?检查@fname的值。 – hellogoodnight
看起来像clasic'加载所有页面加载信息'的问题。请编辑你的问题,并加载到控制代码中,并解释在什么事件和条件下执行 – bradbury9
看一看,不久之前添加它 –