Powered by Blogger.

Sunday, February 23, 2014

Bind dropdownlist using arraylist or hashtable in C#.Net



In this blog we will discuss how we can bind data to a drop downlist using arraylist or hashtable in Asp.Net.

You can check various articles on:

- How to find the difference in retrieving data with and without using index in sql server 2008?

- GAC in Asp.Net

- Implicitely typed variables in C#.Net

Here I have taken 2 dropdownlist name as ddlWebSiteListArrayList and ddlWebSiteListHashTable. And I am binding the ddlWebSiteListArrayList from the array list and binding ddlWebSiteListHashTable from a Hashtable.

Below is the code:

.Aspx code:

 <div>
        Bind From ArrayList:
        <asp:DropDownList ID="ddlWebSiteList" runat="server">
        </asp:DropDownList>
        <br /><br />
        Bind From Hashtable:
        <asp:DropDownList ID="ddlWebSiteListHashTable" runat="server">
        </asp:DropDownList>
    </div>

.cs code:

First we have to include the System.Collections namespace.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class BindDropDownListFromArrayList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownFromArrayList();
            BindDropDownFromHashTable();
        }
    }

    //This function will bind the dropdownlist from ArrayList
    void BindDropDownFromArrayList()
    {
        ArrayList list = new ArrayList();
        list.Add("AspDotNetHelp.com");
        list.Add("SharePointDotNet.com");
        list.Add("EnjoySharePoint.com");
        list.Insert(1, "Fewlines4Biju.com");

        ddlWebSiteList.DataSource = list;
        ddlWebSiteList.DataBind();
    }

    //This function will bind the dropdownlist from Hashtable
    void BindDropDownFromHashTable()
    {
        Hashtable hashItems = new Hashtable();
        hashItems.Add("1", "AspDotNetHelp.com");
        hashItems.Add("2", "SharePointDotNet.com");
        hashItems.Add("3", "EnjoySharePoint.com");
        hashItems.Add("4", "Fewlines4Biju.com");

        ddlWebSiteListHashTable.DataSource = hashItems;
        ddlWebSiteListHashTable.DataTextField = "Value";
        ddlWebSiteListHashTable.DataValueField = "Key";
        ddlWebSiteListHashTable.DataBind();
    }
}

The output is shown in the figure below:




0 comments

Post a Comment