我有一个包含数据库表数据的下拉列表,我想在另一个表中插入此ddl + 2 texbox字段。插入工作但总是先插入默认的dropdownList。我失踪了吗?
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(TextBoxValue.Text))
return;
string connectionString = cs.getConnection();
string insertSql = "INSERT INTO profits(Value,DateCreate,IdCategory,IdUser) VALUES(@Value, @DateCreate,@CategoryId,@UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(insertSql, myConnection);
//параметризация се прави тук за да се избегне SQL Injection
command.Parameters.AddWithValue("@Value", TextBoxValue.Text);
command.Parameters.AddWithValue("@DateCreate", TextBoxData.Text);
command.Parameters.AddWithValue("@CategoryId", DropDownListCategory.SelectedValue);
command.Parameters.AddWithValue("@UserId", cui.getCurrentId());
command.ExecuteNonQuery();
//пренасочваме заявката към същата страница за да се видят новите резултати и да се избегне проблем с дублиране на инсерт при рефреш на страницата
Response.Redirect("~/Profit.aspx");
myConnection.Close();
}
TextBoxValue.Text = string.Empty;
}
答案 0 :(得分:4)
您在每次加载页面时重新绑定列表。将数据绑定代码包装在if (!IsPostBack)
块中。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind the list here...
}
}
答案 1 :(得分:2)
每次按下asp:按钮都会重新加载页面,并且page_load方法中的代码会再次初始化。这就是默认项目始终插入数据库的原因。
将它放在page_load中的代码中:(if(!Page.IsPostback))
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.isPostback)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
}
答案 2 :(得分:1)
使用AppendDataBoundItems属性并将其设置为true,并仅在PostBack上绑定:
How Do I Add an Additional Item To a Databound DropDownList Control in ASP.NET?