Using C#, how can I update a label when I select an item from a ListBox?
Hy,
In my ASP.NET application I have a listbox with multiple items and a label.
How can I update the label text when I select one item from t开发者_Go百科he listbox? For example, if I select 'First' item, then my label text will be 'First'?
Thank you Jeff
Your best bet is to use javascript unless you have a reason to postback to the server.
Personally I like jQuery. It would look something like this:
$('#ListID').change(function() {
$('#LabelID').text(this.val());
});
Try this:
Add OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" to your listbox on the aspx page and in the code behind add something like this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
lblYourLabel.Text = ListBox1.SelectedItem.ToString();
}
This should set the text of your label to the text of the selected item in the listbox.
Hope this helps.
You should enable AutoPostBack on that listbox (in design view arrow in upper right corner on control) and in Page_Load write:
Label.Text = ListBox1.SelectedItem.Text;
But this will cause that every change on listBox reloads a page. You should user JavaScript for this purpose...
Use the SelectedIndexChanged event of the ListBox to set the text of the label to the selected items value.
Something like:
<asp:ListBox ID="listBox" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="listBox_SelectedIndexChanged" />
<asp:Label ID="YourLabel" runat="server" />
and in the codebehind:
protected void listBox_SelectedIndexChanged(object sender, eventargs e) {
YourLabel.Text = listBox.SelectedItem.ToString();
}
精彩评论