在下拉列表中获取所选值的ID

时间:2017-11-29 06:41:56

标签: c# sql asp.net sql-server

我正在尝试在我的数据库中保存数据,因为我试图在我的下拉列表中获取所选项目的ID(主键)。

它始终保存相同的ID。它只保存任何所选项目的第一个ID。如何调整我的代码,以便根据我在下拉列表中选择的内容保存不同的ID

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
    DropDownList1.DataSource = cmd.ExecuteReader();
    DropDownList1.DataTextField = "RoleType";
    DropDownList1.DataValueField = "UserRoleID";
    DropDownList1.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    String ID = DropDownList1.SelectedValue;
    cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
    cmd.Parameters.AddWithValue("UserRoleID", ID);
    cmd.Parameters.AddWithValue("Username", TextBox1.Text);
    cmd.Parameters.AddWithValue("Password", TextBox2.Text);
    cmd.Parameters.AddWithValue("Email", TextBox3.Text);
    cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}

1 个答案:

答案 0 :(得分:2)

您应该检查!IsPostBack

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack) // Add this If condition
    {
        SqlConnection con = new SqlConnection(
        WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
        DropDownList1.DataSource = cmd.ExecuteReader();
        DropDownList1.DataTextField = "RoleType";
        DropDownList1.DataValueField = "UserRoleID";
        DropDownList1.DataBind();
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    String ID = DropDownList1.SelectedValue;
    cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
    cmd.Parameters.AddWithValue("UserRoleID", ID);
    cmd.Parameters.AddWithValue("Username", TextBox1.Text);
    cmd.Parameters.AddWithValue("Password", TextBox2.Text);
    cmd.Parameters.AddWithValue("Email", TextBox3.Text);
    cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}