asp.nettextboxajaxcontroltoolkitextender

ASP.NET Textbox DropDownExtender


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>


Solution

  • You can put the selected item's text into the TextBox if you add a handler for the ListBox's SelectedIndexChanged event:

    Markup:

    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
        <ajaxtoolkit:dropdownextender id="TextBox1_DropDownExtender" dropdowncontrolid="ListBox1"
            runat="server" enabled="True" targetcontrolid="TextBox1"
            highlightbackcolor="WhiteSmoke" />
    </div>
    <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox_SelectedIndexChanged">
        <asp:ListItem>Item 1</asp:ListItem>
        <asp:ListItem>Item 2</asp:ListItem>
        <asp:ListItem>Item 3</asp:ListItem>
    </asp:ListBox>
    

    Code:

    protected void ListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        TextBox1.Text = ListBox1.SelectedItem.Text;
    }
    

    However, this could get really problematic to manage if you have a number of TextBoxes, Extenders and ListBoxes on the page so you might want to consider wrapping the TextBox, Extender and ListBox all up together in a UserControl.