繁体   English   中英

使用C#,当我从列表框中选择一个项目时如何更新标签?

[英]Using C#, how can I update a label when I select an item from a ListBox?

HY,

在我的ASP.NET应用程序中,我有一个包含多个项目和一个标签的列表框。

从列表框中选择一项时,如何更新标签文本? 例如,如果我选择“第一”项目,那么我的标签文本将是“第一”?

谢谢杰夫

除非您有理由回发到服务器,否则最好的选择是使用javascript。

我个人喜欢jQuery 它看起来像这样:

$('#ListID').change(function() {
    $('#LabelID').text(this.val());
});

尝试这个:

在aspx页面上的列表框中添加OnSelectedIndexChanged =“ ListBox1_SelectedIndexChanged”,并在后面的代码中添加以下内容:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     lblYourLabel.Text = ListBox1.SelectedItem.ToString();
 }

这应该将标签的文本设置为列表框中所选项目的文本。

希望这可以帮助。

您应该在该列表框(在控件右上角的设计视图箭头中)和Page_Load中启用AutoPostBack:

Label.Text = ListBox1.SelectedItem.Text;

但这将导致listBox上的所有更改都重新加载页面。 为此,您应该使用JavaScript。

使用ListBox的SelectedIndexChanged事件将标签的文本设置为所选项目的值。

就像是:

<asp:ListBox ID="listBox" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="listBox_SelectedIndexChanged"  />
<asp:Label ID="YourLabel" runat="server" />

并在后面的代码中:

protected void listBox_SelectedIndexChanged(object sender, eventargs e) {
     YourLabel.Text = listBox.SelectedItem.ToString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM