当 asp:ListBox 更改所选项目时更新 asp:TextBox

Update an asp:TextBox when a asp:ListBox changes selected item

我是 ASP.Net 的新手,我有以下疑问:
有没有办法在 ListBox 的选定项发生更改时更新 TextBox 的内容? 我有这个:

<asp:ListBox ID="myListBox" runat="server" Width="200px"></asp:ListBox>

<asp:TextBox ID="myTextBox" runat="server" Width="200" />

ListBox 上的项目是 Page_Load 中添加的字符串。
基本上,我想将选定的项目放在 TextBox 中,而不必进行 PostBack 并在代码隐藏中执行此操作(为了提高效率)。
提前致谢!

当然可以。这就是客户端编程的目的 (JavaScript)。

当服务器将 ListBox 呈现为 HTML 时,它会转换为 HTML select 元素。所以你可以使用这个代码:

<asp:ListBox ID="myListBox" runat="server" Width="200px"></asp:ListBox>
<asp:TextBox ID="myTextBox" runat="server" Width="200" />

<!-- Below we're adding the reference to jQuery, which is publicly hosted on a CDN -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

<!-- Here's where our JavaScript is -->
<script type="text/javascript">
$(function(){
    $('#<%=myListBox.ClientID %>').change(function(){ //when the select value of the list box changes, we're going to call the below code
        $('#<%=myTextBox.ClientID %>').val($('#<%=myListBox.ClientID %>').val()); // Set the value of the text box to the value of the list box.
    });
});
</script>

请注意,我使用的是 jQuery 库,这是一个非常流行的 JavaScript 框架,可以简化客户端编码。

请注意,我使用特殊语法将 ListBoxTextBoxClientID 嵌入到 JavaScript 中。这是因为JavaScript运行在客户端,ListBoxTextBox的ID可以根据ClientIDMode从服务端变为客户端(即一些让很多 Web 窗体开发人员感到困惑的东西)控件指定的。嵌入 ClientID 确保客户端上 JavaScript 中使用的 ID 与客户端上 select 元素的 ID 相匹配。