Practical-10
Problem Statement
Write a program to add the value of Text Box into Dropdown List and List box Controls.
Solution
To add the value of a Text Box into Dropdown List and List Box controls in ASP.NET, follow the steps below:
- Create a new ASP.NET Web Application project in Visual Studio.
- Add a new Web Form to the project by right-clicking on the project in the Solution Explorer, selecting "Add" > "Web Form".
- Rename the Web Form to "Default.aspx".
- Open the "Default.aspx" file and design the user interface as per your requirements using HTML and ASP.NET controls.
- Add the following controls to the "Default.aspx" form:
- TextBox control:
<asp:TextBox ID="txtValue" runat="server"></asp:TextBox> - Button control:
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click"></asp:Button> - DropDownList control:
<asp:DropDownList ID="ddlValues" runat="server"></asp:DropDownList> - ListBox control:
<asp:ListBox ID="lstValues" runat="server"></asp:ListBox>
- TextBox control:
- 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)
{
ddlValues.Items.Add(new ListItem("Value 1", "1"));
ddlValues.Items.Add(new ListItem("Value 2", "2"));
ddlValues.Items.Add(new ListItem("Value 3", "3"));
lstValues.Items.Add(new ListItem("Value 1", "1"));
lstValues.Items.Add(new ListItem("Value 2", "2"));
lstValues.Items.Add(new ListItem("Value 3", "3"));
}
}
- Write the following code in the click event handler of the "btnAdd" button to add the value of the Text Box into the DropDownList and ListBox controls:
protected void btnAdd_Click(object sender, EventArgs e)
{
string value = txtValue.Text;
ddlValues.Items.Add(new ListItem(value, value));
lstValues.Items.Add(new ListItem(value, value));
txtValue.Text = "";
}
- Build and run the application to see the functionality of adding the value of the Text Box into the DropDownList and ListBox controls.
This completes the solution for adding the value of a Text Box into Dropdown List and List Box controls in ASP.NET.