Introduction:
Hello friends! In this tutorial, we'll explore a useful technique in ASP.NET – displaying serial numbers for selected items in a ListBox and presenting them with commas. This can be beneficial when you want to show a numbered list of selected items in a user-friendly format. Let's dive into the code and understand how to achieve this.
Creating the Page:
To get started, we'll create an ASP.NET page containing a ListBox, a Button, and a Label. The ListBox will allow multiple selections, and we'll use C# code-behind to handle the logic. Here's a snippet of the HTML code for our page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBox-with-Comma.aspx.cs" Inherits="Example_ListBox_with_Comma" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"
Width="325px">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Asia</asp:ListItem>
<asp:ListItem>Europe</asp:ListItem>
<asp:ListItem>North America</asp:ListItem>
<asp:ListItem>South America</asp:ListItem>
<asp:ListItem>Africa</asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add"
Width="84px" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
C# Code:
Now, let's take a look at the C# code-behind that handles the logic for adding serial numbers and displaying the selected items with commas:
protected void Button1_Click(object sender, EventArgs e)
{
int j=1;
if (ListBox1.SelectedItem.Text == "Select")
{
Label1.Text = "No Items Selected...";
}
else
{
string get_soft_skills = "";
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
get_soft_skills += j.ToString() + ". " + ListBox1.Items[i].Value + ",<br/> ";
Label1.Text = get_soft_skills;
j++;
}
}
}
}
Explanation:
- The ListBox allows multiple selections, and we handle the logic in the Button1_Click event.
- We initialize a serialNumber variable to keep track of the item numbers.
- If no items are selected or the "Select" item is chosen, we display a message in the Label.
- For each selected item, we append the serial number, item value, and a line break to the selectedItems string.
- Finally, we set the Label's text to the formatted string.
Conclusion:
By following this tutorial, you've learned how to enhance the presentation of selected ListBox items by adding serial numbers and displaying them with commas. This can improve the user experience and make your ASP.NET web application more user-friendly. Feel free to customize the code to fit your specific requirements and explore further enhancements!
0 Comments