Skip to main content

Practical-9

Problem Statement​

Write a program to demonstrate different common Control.

Solution​

To demonstrate different common controls in ASP.NET, follow the steps below:

  1. Create a new ASP.NET Web Application project in Visual Studio.
  2. Add a new Web Form to the project by right-clicking on the project in the Solution Explorer, selecting "Add" > "Web Form".
  3. Rename the Web Form to "Default.aspx".
  4. Open the "Default.aspx" file and design the user interface as per your requirements using HTML and ASP.NET controls.
  5. Add different common controls to the "Default.aspx" form such as:
    • TextBox control: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    • Button control: <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
    • Label control: <asp:Label ID="lblMessage" runat="server"></asp:Label>
    • CheckBox control: <asp:CheckBox ID="chkAgree" runat="server" Text="I agree to the terms and conditions"></asp:CheckBox>
    • RadioButton control: <asp:RadioButton ID="rbMale" runat="server" Text="Male"></asp:RadioButton>
    • DropDownList control: <asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
    • ListBox control: <asp:ListBox ID="lstColors" runat="server"></asp:ListBox>
  6. In the code-behind file, write the following code in the Page_Load event handler to populate the DropDownList and ListBox controls:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCountry.Items.Add(new ListItem("USA", "1"));
ddlCountry.Items.Add(new ListItem("Canada", "2"));
ddlCountry.Items.Add(new ListItem("UK", "3"));

lstColors.Items.Add(new ListItem("Red", "1"));
lstColors.Items.Add(new ListItem("Green", "2"));
lstColors.Items.Add(new ListItem("Blue", "3"));
}
}
  1. Write the following code in the click event handler of the "btnSubmit" button to display the selected values from the controls:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string message = "Hello, " + name + "!";

if (chkAgree.Checked)
{
message += " You agreed to the terms and conditions.";
}
else
{
message += " You did not agree to the terms and conditions.";
}

if (rbMale.Checked)
{
message += " You selected Male.";
}
else
{
message += " You did not select Male.";
}

string country = ddlCountry.SelectedItem.Text;
message += " You selected " + country + " from the DropDownList.";

string colors = "";
foreach (ListItem item in lstColors.Items)
{
if (item.Selected)
{
colors += item.Text + ", ";
}
}
colors = colors.TrimEnd(',', ' ');
message += " You selected " + colors + " from the ListBox.";

lblMessage.Text = message;
}
  1. Build and run the application to see the different common controls in action.

This completes the solution for demonstrating different common controls in ASP.NET.