我有一个包含数据库表数据的下拉列表,我想在另一个表中插入这个 ddl + 2 texbox 字段。插入工作但始终插入默认的下拉列表女巫首先显示。我错过了什么?
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;
}