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;开发者_C百科
}
</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>
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()">
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.
精彩评论