我有这个文本框:
<asp:TextBox ID="txtDescription" runat="server" Height="90%" TextMode="MultiLine" Width="90%"></asp:TextBox>
我设置了它的&#39;文字值:
description = reader["Description"].ToString();
txtDescription.Text = description;
这是用于编辑&#34;描述&#34;所以我在框中有现有的描述,然后想要更改框中最后的文本。
但是我这样做:
string newDecription = txtDescription.Text;
,该值是最初设置的值。获取文本值的上述代码在提交按钮上运行,因此不能以某种方式运行并在编辑之前获取值。
CONTEXT
protected void Page_Load(object sender, EventArgs e)
{
getValues();
}
string ID = 1;
protected void getValues()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand("SELECT Name,Stock,Price250g,Price1kg,Description,StockOrdered FROM Stock WHERE id = @ID", conn))
{
comm.Parameters.AddWithValue("@ID", ID);
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
price250g = reader["Price250g"].ToString();
price1kg = reader["Price1kg"].ToString();
name = reader["Name"].ToString();
description = reader["Description"].ToString();
stock = reader["Stock"].ToString();
stockOrdered = Convert.ToBoolean(reader["StockOrdered"].ToString());
lblName.Text = name;
lbl250g.Text += price250g.Remove(price250g.Length - 2);
lbl1kg.Text += price1kg.Remove(price1kg.Length - 2);
lblStock.Text = stock + "g";
cbStockOrdered.Checked = stockOrdered;
txtDescription.Text = description;
}
}
}
}
private void addAddressToOrder()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Stock SET Name=@name, Stock=@stock, Price250g=@price250, Price1kg=@price1kg, Description=@description, StockOrdered=@ordered WHERE Id=@ID", conn))
{
cmd.Parameters.AddWithValue("@ID", ID);
cmd.Parameters.AddWithValue("@description", txtDescription.Text);
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@price250", txtPrice250g.Text);
cmd.Parameters.AddWithValue("@price1kg", txtPrice1kg.Text);
stock = ddAddStock.SelectedValue + stock;
cmd.Parameters.AddWithValue("@stock", stock);
cmd.Parameters.AddWithValue("@ordered", cbStockOrdered.Checked);
conn.Open();
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
addAddressToOrder();
Response.Redirect("~/Admin/AdminHome.aspx");
}
答案 0 :(得分:2)
执行此操作时通常会发生这种情况:
protected void Page_Load(object sender, EventArgs e)
{
// other code
txtDescription.Text = description;
}
原因是因为page lifecycle events。 Page_Load
每次加载页面时都会执行。这包括回发。 (毕竟,您需要加载页面才能与之交互。)它在之前运行任何按钮处理程序或其他类似的控件事件。因此,如果在您从文本框中读取值之前执行了将值写入文本框的代码,那么它将覆盖该值。
Page_Load
(或类似页面初始化事件)中不应在回发上运行的任何代码都需要包含在条件中:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// other code
txtDescription.Text = description;
}
}