Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

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

Oct 18, 2014
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.

Description:
  
In previous articles I explained Cascading dropdownlist example in asp.net, highlight gridview records based on search in asp.net, filter gridview records based on dropdown selection in asp.net and many articles relating to
asp.net, c#,vb.net and JQuery. Now I will explain how to add items to dropdownlist programmatically in asp.net using c# and vb.net.

To implement this first create new application and write the code in aspx page like 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

C# 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));
        }
    }
}

VB.NET Code


Partial Class VbCode
    Inherits System.Web.UI.Page
    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
        If txtName.Text.Trim() <> "" Then
            ddlUsername.Items.Add(New ListItem(txtName.Text, txtName.Text))
        End If
    End Sub
End Class

Demo


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

0 comments :

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.