Tuesday, January 4, 2011

Bind Enum to Dropdown List With Sorting

/*    Create Enum Data Block First */

public enum DignosisOrderType
    {
        All = 0,
        General = 1,
        Uveitis = 2,
        Coag = 3,
        PreOp = 4,
        Tests = 5,
        RP = 6     }  
      /*   Now Creat a method to bind this drop download- pass control and Enum Data to
        function */        

    public static void BindDropDownByEnum(ref DropDownList dropDownList,
                        Type enumDataSource)
    {
        DataTable dtTemp = new DataTable();  /*create datatable and follow the steps of
                                               ADO to bind with dropdown list */
        dtTemp.Columns.Add("ID");
        dtTemp.Columns.Add("Name");
        string[] names = Enum.GetNames(enumDataSource);
        Array values = Enum.GetValues(enumDataSource);
        for (int i = 0; i < names.Length; i++)        
        {
            DataRow drTemp = dtTemp.NewRow();
            drTemp["ID"] = Convert.ToInt32((DignosisOrderType)Enum.Parse
                        (typeof(DignosisOrderType), names[i])).ToString();
            drTemp["Name"] = names[i];
            dtTemp.Rows.Add(drTemp);
        }
        DataView dvTemp = new DataView(dtTemp);
        dvTemp.Sort = "Name";
        dropDownList.DataTextField = "Name";
        dropDownList.DataValueField = "ID";
        dropDownList.DataSource = dvTemp;
        dropDownList.DataBind();
      
    }
Call Above Method
BindDropDownByEnum(ref DropDownList1, typeof(DignosisOrderType));

No comments :

Post a Comment