How to Bind DropDownList using Complex DataType in ASP.NET

Step-1: Define class properties in class
Step-2: Create a List<DataType> object in code file.
Step-3: Add fields to the list.
Step-4: Bind DropDownlist with list
Step-5: Assign DataMember to the DropDownList.


Create a class file in ASP.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Fruits
/// </summary>
public class Fruits
{
    public string  Fruits_Name { get; set; }
    public decimal Fruits_price { get; set; }
 

Take a DropDownList on Design window
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

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

public partial class Default5 : System.Web.UI.Page
{
    List<Fruits> listitem = new List<Fruits>();

    protected void Page_Load(object sender, EventArgs e)
    {
        listitem.Add(new Fruits() { Fruits_Name = "Apple", Fruits_price = 45.40M });
        listitem.Add(new Fruits() { Fruits_Name = "Mango", Fruits_price = 30.40M });
        listitem.Add(new Fruits() { Fruits_Name = "Orange", Fruits_price = 36.40M });
        listitem.Add(new Fruits() { Fruits_Name = "grapes", Fruits_price = 89.40M });
        DropDownList1.DataSource = listitem;
       DropDownList1.DataTextField = "Fruits_Name";
        DropDownList1.DataBind();

    }
}

Output
How to Bind DropDownList using Complex DataType in ASP.NET

How to Bind DropDownList using Complex DataType in ASP.NET How to Bind DropDownList using Complex DataType in ASP.NET Reviewed by Jacob Lefore on September 26, 2013 Rating: 5

No comments