c# - 添加选项到下拉列表

标签 c# asp.net

我有一个包含多个值的下拉列表。我有一个名为“其他”的列表项。选择其他时,我想生成一个带有必填字段验证器的文本框。我是这样写的:

标记:

<asp:DropDownList ID="dl_test_name" runat="server" 
                  OnSelectedIndexChanged="SelectedIndexChanged" 
                  Height="22px" Width="103px">
    <asp:ListItem>Science</asp:ListItem>
    <asp:ListItem>Maths</asp:ListItem>          
    <asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb_other" runat="server" Width="94px" Visible="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" 
                            ControlToValidate="tb_other" ErrorMessage="*">   
</asp:RequiredFieldValidator>

代码隐藏:

protected void SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList dropDownList = (DropDownList)sender;
    if (dropDownList.SelectedValue == "Other")
    {
        tb_other.Enabled = true;
        tb_other.Text = string.Empty;
        tb_other.Visible = true;
    }
    else
    {
        tb_other.Enabled = false;
        tb_other.Text = dropDownList.SelectedValue;
    }
}

但在选择任何列表项时,控件不会转到 SelectedIndexChanged 事件。只有在重新加载页面后它才能工作。

问题是什么?

最佳答案

要使您的 DropDownList 回发到服务器,您需要使用 AutoPostback 属性,如下所示:

<asp:DropDownList ID="dl_test_name" runat="server" 
                  OnSelectedIndexChanged="SelectedIndexChanged" 
                  Height="22px" Width="103px" AutoPostBack="true">

关于c# - 添加选项到下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18669958/

相关文章:

c# - 从数据库自动完成

c# - 为什么异步回调套接字方法通常是静态的?

c# - 如何使用来自不同项目的类

c# - 处理存储库中未找到的对象

c# - WCF CORS 已设置,但仍然出现 No 'Access-Control-Allow-Origin' header is present

c# - MVC - 如何哈希和加盐

c# - 绑定(bind)列表的 ObservableCollection

javascript - 有关 JavaScript 和文本区域的帮助

c# - 单击 asp.net 按钮时如何关闭 Html 窗口?

c# - 如何在 ASP NET 中通过公共(public) API 通过 HTTP 发布文件?