在 ASP.NET 中实现可编辑的 DropDownList编辑、ASP、NET、DropDownList

2023-09-07 15:42:37 作者:童年的草坪早已失去了光彩

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.

asp.net中通过DropDownList的值去控制TextBox是否可编写的实现代码

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.