C# 基于文本框值更新数据库表
我正在尝试根据文本框值更新数据库表。但我无法在数据库中获取新的修改值 这是我的代码,它在来自数据库的文本框中显示信息C# 基于文本框值更新数据库表,c#,asp.net,sql-server-2008,ado.net,C#,Asp.net,Sql Server 2008,Ado.net,我正在尝试根据文本框值更新数据库表。但我无法在数据库中获取新的修改值 这是我的代码,它在来自数据库的文本框中显示信息 protected void Info() { string sID = Request.QueryString["ID"]; string sSql = "select * from [fn_Items]('"+sID+"')"; DataTable tbl1 = new DataTable(); string sEr = myClass.Fil
protected void Info()
{
string sID = Request.QueryString["ID"];
string sSql = "select * from [fn_Items]('"+sID+"')";
DataTable tbl1 = new DataTable();
string sEr = myClass.FillupTable(sSql, ref tbl1);
if (tbl1.Rows.Count > 0)
{
DataRow rd = tbl1.Rows[0];
txtName.Text = rd["Name"].ToString();
txtCategory.Text = rd["Category"].ToString();
DateTime mStart;
DateTime mFinish;
Boolean b = false;
b = DateTime.TryParse(rd["start"].ToString(), out mStart);
b = DateTime.TryParse(rd["end"].ToString(), out mFinish);
txtStart.Text = mStart.ToString("dd-MMM-yyyy");
txtend.Text = mFinish.ToString("dd-MMM-yyyy");
txtDescription.Text = rd["Description"].ToString();
}
}
现在,当用户修改文本框数据并单击“保存”时,数据库中的数据应该会更改。以下是我的点击事件:
protected void btnSave_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new
SqlConnection("Data Source=MSSQLSERVER2008;Initial Catalog=Items_2;Persist Security Info=True;User ID=sa;Password=password"))
{
string query = "UPDATE tbl_Items SET Name = @Name,Category=@Category,start = @start, end = @End,Description = @Description where ID = @ID ";
SqlCommand cmd = new SqlCommand(query, sqlConn);
cmd.Parameters.AddWithValue("@ID",txtID.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Category", Category.Text);
cmd.Parameters.AddWithValue("@start", txtStart.Text);
cmd.Parameters.AddWithValue("@end",txtend.Text);
cmd.Parameters.AddWithValue("@Description", txtDescription.Text);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error " + ex.Message);
}
}
在这里,当更新时,我在文本框中获取数据库中存在的值,我需要在其中获取修改后的值。如何获得修改后的值?在触发btnSave的单击事件之前,先触发页面加载事件。使用户可以消除该问题
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Info();
}
}
调试时,是否在单击事件中看到值?您确定它们的标签正确吗?当Iam调试时,我从Info()获取以前的值。我没有得到更改的值。请注意,您应该验证文本输入。您当前的代码易受SQL注入攻击。例如,假设在txtID.Text中,我输入值
12345'drop table tbl_items
,我将能够删除您的表。我将进行一次旋转。:)你需要!iPostback在页面加载事件中类似于-Page_Load(objectsender,EventArgs e){if(!IsPostBack){Info();}}}谢谢@Win是的我忘了在页面加载中添加iPostback…非常感谢!!!!!