You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET WebForms中实现支持自定义输入的类ListBox控件?

在ASP.NET WebForms中实现可自由输入并回车选中的控件

方案一:原生TextBox + JavaScript(无第三方依赖)

不想引入第三方控件的话,用TextBox搭配前端JS就能实现需求,还能通过样式调整让它外观接近ListBox。

步骤与代码

  1. 在ASPX页面添加TextBox,设置多行模式和样式:
<asp:TextBox ID="txtCustomList" runat="server" 
    TextMode="MultiLine" 
    Rows="8" 
    Style="width: 220px; border: 1px solid #ccc; padding: 4px;"
    onkeydown="onEnterPress(event, this)"></asp:TextBox>
  1. 编写JavaScript监听回车事件,实现输入后选中内容:
function onEnterPress(event, textBox) {
    if (event.keyCode === 13) {
        event.preventDefault(); // 阻止表单默认提交行为
        // 选中当前输入的最后一行内容
        var currentValue = textBox.value;
        var lastLineStart = currentValue.lastIndexOf('\n') + 1;
        textBox.setSelectionRange(lastLineStart, currentValue.length);
    }
}

说明

  • 设置TextMode="MultiLine"和Rows属性,让控件显示为多行列表样式
  • 回车时阻止表单提交,直接选中当前输入的文本内容
  • 如果只需要单行输入,把TextMode改回SingleLine,JS里直接调用textBox.select()即可

方案二:使用AjaxControlToolkit ComboBox(支持自定义输入)

允许引入第三方控件的话,AjaxControlToolkit的ComboBox天生支持自定义输入(无需校验输入项是否在预定义列表),搭配简单JS就能实现回车选中效果。

步骤与代码

  1. 先在页面注册AjaxControlToolkit控件:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
  1. 添加ComboBox控件并配置:
<ajaxToolkit:ComboBox ID="cboCustomInput" runat="server" 
    AllowCustomText="true" 
    AutoCompleteMode="None" 
    Width="220px" 
    DropDownStyle="DropDownList">
</ajaxToolkit:ComboBox>
  1. 补充JS监听回车事件:
document.getElementById('<%= cboCustomInput.ClientID %>').addEventListener('keydown', function(e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        this.select();
    }
});

说明

  • AllowCustomText="true"是核心配置,允许用户输入不在预定义列表中的内容
  • DropDownStyle="DropDownList"让控件外观更接近ListBox
  • 回车事件中直接选中当前输入的文本,满足需求

内容的提问来源于stack exchange,提问作者Bumda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:34:54