我有州和城市的下拉菜单。当用户从第一个下拉列表中选择任何州时,城市会反映在另一个下拉列表中。我在城市下拉列表中给出了其他选项。这样用户就可以为相应的添加添加自己的城市。这里默认情况下隐藏了文本框的内容,当用户从城市下拉列表中选择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>
<asp:button id="btnAddDropDown" runat="server" width="63" text="Add" causesvalidation="false" />
</td>
</tr>
请帮忙。
答案 0 :(得分:0)
我这样添加它并且有效。
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));
}
}