ASP.NET Textbox DropDownExtender

Troy Mitchel picture Troy Mitchel · Mar 2, 2011 · Viewed 16.4k times · Source

How to get the value from the dropdown to return to the TextBox? The following does not work. You can select the item from list though.

<body>
<form id="form1" runat="server">
<script type="text/javascript">
    function pageLoad() {
        //Same Width
        $get('ListBox1').style.width = $get('TextBox1').clientWidth;
    }
</script>
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ToolkitScriptManager>
<div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <ajax:DropDownExtender ID="TextBox1_DropDownExtender" DropDownControlID="ListBox1"
        runat="server" DynamicServicePath="" Enabled="True" TargetControlID="TextBox1"
        HighlightBackColor="WhiteSmoke">
    </ajax:DropDownExtender>
</div>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True">
    <asp:ListItem>Item 1</asp:ListItem>
    <asp:ListItem>Item 2</asp:ListItem>
    <asp:ListItem>Item 3</asp:ListItem>
</asp:ListBox>
</form>

Answer

Dillie-O picture Dillie-O · Mar 2, 2011

You'll want to wire up the onchange event to your ListItem to call a JavaScript method that gets the text from the item that was selected. Your JavaScript code would look something like this (not tested):

    function setOptionText()
    {
       var ddl = $get('ListBox1');
       var index = ddl.selectedIndex

       $get('TextBox1').value = ddl.options[index].value;
    }

Then you wire up your ListBox control accordingly. Note that you no longer need the AutoPostBack option since JavaScript is handling setting the text.

<asp:ListBox ID="ListBox1" runat="server" onchange="return setOptionText()">