Monday, December 29, 2014

ASP.Net - Add Items to Dropdownlist Programmatically on Button Click in C#


Here I will explain how to add items to dropdownlist programmatically on button click in using c# and or dynamically add items to dropdownlist on button click in using c# and

To implement this first create new application and write the code in aspx page as shown below
<html xmlns="">
<head id="Head1" runat="server">
<title>Dynamically Add items to dropdownlist in</title>
<form id="form1" runat="server">
<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"/>

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