Implementing an editable DropDownList in ASP.NET(在 ASP.NET 中实现可编辑的 DropDownList)
问题描述
What's the most elegant way of implementing a DropDownList in ASP.NET that is editable without using 3rd party components.
As a last resort I will probably try using a TextBox with an AutoCompleteExtender with an image to 'drop down' the list; or a TextBox overlapping a HTML Select with some JavaScript to fill values from the Select to the TextBox. But I'm really hoping there is a more terse and maintainable solution.
Thanks in advance.
One Control on a Page
You can follow this simple example for an Editable DropDownlist on Code Project that uses standard ASP.NET TextBox and DropDownList controls combined with some JavaScript.
However, the code did not work for me until I added a reference to get the ClientID values for the TextBox and DropDownList:
<script language="javascript" type="text/javascript">
function DisplayText()
{
var textboxId = '<% = txtDisplay.ClientID %>';
var comboBoxId = '<% = ddSelect.ClientID %>';
document.getElementById(textboxId).value = document.getElementById(comboBoxId).value;
document.getElementById(textboxId).focus();
}
</script>
<asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>
<asp:DropDownList ID="ddSelect" style="width:140px" runat="server">
<asp:ListItem Value="test1" >test1</asp:ListItem>
<asp:ListItem Value="test2">test2</asp:ListItem>
</asp:DropDownList>
Finally, in the code behind just like in the original example, I added the following to page load:
protected void Page_Load(object sender, EventArgs e)
{
ddSelect.Attributes.Add("onChange", "DisplayText();");
}
Multiple Controls on a Page
I placed all of the above code in its own ASCX User Control to make it reusable across my project. However, the code as presented above only works if you require just one editable DropDownList on a given page.
If you need to support multiple custom DropDownList controls on a single page, it is necessary to set the JavaScript function name to be unique to avoid conflicts. Do this by once again using the ClientID:
in the ASCX file:
function DisplayText_<% = ClientID %>(){...}
in the code behind:
/// ...
ddSelect.Attributes.Add("onChange", "DisplayText_" + ClientID + "();");
///..
This is one way to avoid using 3rd party controls.
这篇关于在 ASP.NET 中实现可编辑的 DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 ASP.NET 中实现可编辑的 DropDownList
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
