代码之家  ›  专栏  ›  技术社区  ›  hud

在下拉列表中动态添加值

  •  0
  • hud  · 技术社区  · 10 年前

    我有一个州和市的下拉列表。当用户从第一个下拉列表中选择任何状态时,城市将反映在另一个下拉列表。我在城市下拉列表中给出了OTHER选项。以便用户可以为相应的添加添加自己的城市。在这里,默认情况下文本框是隐藏的,当用户从城市下拉列表中选择OTHER选项时,它是可见的。我希望文本框值插入下拉列表中。我尝试使用下面的代码和帮助按钮,但它不适用于我。请查看代码。

     protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlLocation.SelectedItem.Text == "Other")
        {
            txtOtherCity.Visible = true;
        }
        else {
            txtOtherCity.Visible = false;
        }
    }
    protected void btnAddDropDown_Click(object sender, EventArgs e)
    {
        conn = new SqlConnection();
        try
        {
            conn.Open();
            if (txtOtherCity.Text != "")
            {
                ddllocation1.Items.Insert(0, txtOtherCity.Text);
                txtOtherCity.Text = "";
            }
            string commandtext = "Insert into Career.Job Values('" + txtOtherCity.Text.Trim() + "') where Location='" + ddllocation1.SelectedItem.Text + "'";
            SqlCommand cmd = new SqlCommand(commandtext);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);//You Can Haave Messagebox here
        }
        finally
        {
            conn.Close();
        }
    }
    

    此外,请参见下拉列表、文本框和按钮的html代码

      <tr>
        <td class="td">Location/City</td>
        <td>
            <asp:dropdownlist cssclass="txtfld-popup" id="ddlLocation" runat="server" autopostback="true" onselectedindexchanged="ddlLocation_SelectedIndexChanged"></asp:dropdownlist>
            <asp:requiredfieldvalidator cssclass="error_msg" id="reqLocation" controltovalidate="ddlLocation" runat="server" errormessage="Please enter location" initialvalue="--Select--" setfocusonerror="true"></asp:requiredfieldvalidator>
        </td>
    </tr>
    <tr>
        <td>
            <asp:textbox id="txtOtherCity" runat="server" visible="false" cssclass="txtfld-popup"></asp:textbox>
            &nbsp;&nbsp;&nbsp;
                        <asp:button id="btnAddDropDown" runat="server" width="63" text="Add" causesvalidation="false" />
        </td>
    </tr>
    

    请帮忙。

    1 回复  |  直到 10 年前
        1
  •  0
  •   hud    10 年前

    我这样加了它,效果很好。

      protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlLocation.SelectedItem.Text == "Other")
        {
            txtOtherCity.Visible = true;
        }
        else {
            txtOtherCity.Visible = false;
        }
    }
    protected void btnAddDropDown_Click1(object sender, EventArgs e)
    {
        string city = txtOtherCity.Text.Trim();
        if (!string.IsNullOrEmpty(city))
        {
            ddlLocation.Items.Add(new ListItem(city, city));
        }
    }