Monday, October 6, 2014

How to Bind 2 or more columns data from database table to DropDownList in asp.net

In DropDownList everyone knows that there is DataTextField and DataValueField commonly we bind one column to DataTextField and one column to DataValueField from DataTable or any DataReaders etc.
If we want to bind 2 or more columns to DataTextField of DropDownList we use Dictionary Class and by using that we bind to dropdownlist.

In Default5.aspx Page

Add one DropDownlist to a page as shown in below.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
  <asp:DropDownList runat="server" ID="ddlStates" Width="30%"></asp:DropDownList>
    </form>
</body>
</html>


In Default5.cs Page

Create one method that will retrieve records from database as shown below

 protected void PopulateStates()
    {
        //using metod am getting all states from table storing in datatable
        dt = Acls.selectUSAStateMaster();
        //Creating Dictionary with string datatype
        Dictionary<string, string> lst = new Dictionary<string, string>();
        //Using foreach am adding all rows to dictionary
        foreach (DataRow row in dt.Rows)
        {
            //Add values to Dictionary
            string val = row["StateID"].ToString() + "( " + row["State"].ToString() + " )";
            lst.Add(row["State"].ToString(), val);
        }
        //finnaly am assigning DataSouce to DropDownList as Dicyionary object 
        //In Dictionary rows will be stored as 'KEY','VALUE' pairs so am assigning KEY and VALUE as datatextfiled and datavaluefield
        ddlstate.DataSource = lst;
        ddlstate.DataTextField = "value";
        ddlstate.DataValueField = "key";
        ddlstate.DataBind();
        //Adding new listitem as Select to droipdownlist
        ListItem item = new ListItem("Select ", "0");
        ddlstate.Items.Insert(0, item);

    }


Call this method in ISPOSTBACK or POSTBACK where ever you want and execute you will get output as shown below



No comments:

Post a Comment