如何从下拉列表中获取值以返回TextBox? 以下不起作用。您可以从列表中选择项目。
<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>
答案 0 :(得分:2)
您需要将onchange事件连接到ListItem,以调用JavaScript方法,该方法从所选项目中获取文本。您的JavaScript代码看起来像这样(未经测试):
function setOptionText()
{
var ddl = $get('ListBox1');
var index = ddl.selectedIndex
$get('TextBox1').value = ddl.options[index].value;
}
然后相应地连接ListBox控件。请注意,您不再需要AutoPostBack选项,因为JavaScript正在处理设置文本。
<asp:ListBox ID="ListBox1" runat="server" onchange="return setOptionText()">
答案 1 :(得分:1)
如果为ListBox的SelectedIndexChanged事件添加处理程序,则可以将所选项目的文本放入TextBox中:
标记:
<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>
代码:
protected void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = ListBox1.SelectedItem.Text;
}
但是,如果您在页面上有许多TextBox,Extender和ListBox,那么管理起来可能会遇到问题,因此您可能需要考虑在UserControl中将TextBox,Extender和ListBox全部包装在一起。