Hello,
You can easily achieve this by setting Text & Value pair in the ListBox. You do not need to use if condition here. When you select an item the corresponding value will show in the Label. You can use the
OnSelectedIndexChanged event so that when you change your selection the value will change in the label.
Here is the code snippet for you if you are using asp.net web form.
<div>
Selected Item: <asp:Label ID="PgeTitleLbl" runat="server"></asp:Label>
<br /><br />
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ShowValueInLabel" AutoPostBack="true">
<asp:ListItem Text="Plant" Value="Flowers"></asp:ListItem>
<asp:ListItem Text="sugar" Value="sweet"></asp:ListItem>
<asp:ListItem Text="eyes" Value="face"></asp:ListItem>
</asp:ListBox>
</div>
In code behind file for the method ShowValueInLabel:
protected void ShowValueInLabel(object sender, EventArgs e)
{
PgeTitleLbl.Text = ListBox1.SelectedValue;
}
This is the easy process. If you want to display items in Listbox from database, you can use so. If still you want to use button click you can do so.
Change the ListBox AutoPostBack=false.
Add Button to the cshtml.
<asp:Button ID="NxtButton" runat="server" Text="Show Item" OnClick="ShowListItem" />
Add the method ShowListItem in Code behind file:
protected void ShowListItem(object sender, EventArgs e)
{
PgeTitleLbl.Text = ListBox1.SelectedValue;
}
Hope this helps.