Slip-8 Q.A) Problem Statement
Q. List of employees is available in a listbox. Write an ASP.Net application to add selected or all records from the listbox to a TextBox (assume multi-line property of TextBox is true). 15 Marks
Answer:
WebForm1.aspx (Design Page)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Employee List Program</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Employee List</h2>
<!-- ListBox -->
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem>Rahul</asp:ListItem>
<asp:ListItem>Priya</asp:ListItem>
<asp:ListItem>Amit</asp:ListItem>
<asp:ListItem>Neha</asp:ListItem>
<asp:ListItem>Suresh</asp:ListItem>
</asp:ListBox>
<br /><br />
<!-- Buttons -->
<asp:Button ID="btnSelected" runat="server"
Text="Add Selected"
OnClick="btnSelected_Click" />
<asp:Button ID="btnAll" runat="server"
Text="Add All"
OnClick="btnAll_Click" />
<br /><br />
<!-- Multiline TextBox -->
<asp:TextBox ID="TextBox1" runat="server"
TextMode="MultiLine"
Rows="8" Columns="30">
</asp:TextBox>
</div>
</form>
</body>
</html>
WebForm1.aspx.cs (Code Behind)
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// Add Selected Employees
protected void btnSelected_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
TextBox1.Text += item.Text + Environment.NewLine;
}
}
}
// Add All Employees
protected void btnAll_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
foreach (ListItem item in ListBox1.Items)
{
TextBox1.Text += item.Text + Environment.NewLine;
}
}
}
}
