Introduction:
Here I will explain how to add items to dropdownlist programmatically on button click in asp.net using c# and vb.net or dynamically add items to dropdownlist on button click in asp.net using c# and vb.net.
To implement this first create new application and write the code in aspx page as shown below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>Dynamically Add items to dropdownlist in asp.net</title>
</head>
<body>
<form id="form1"
runat="server">
<div>
<b>Enter Name</b><asp:TextBox ID="txtName" runat="server" /><asp:Button ID="btnAdd"
runat="server" Text="Add Items" onclick="btnAdd_Click" /><br />
Select UserName: <asp:DropDownList ID="ddlUsername" runat="server"/>
</div>
</form>
</body>
</html>Now open code behind file and write the following code
using System;
using System.Web.UI.WebControls;
public partial class _Default :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
}
protected void
btnAdd_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() != "")
{
ddlUsername.Items.Add(new ListItem(txtName.Text, txtName.Text));
}
}
}
No comments:
Post a Comment