How to use option group with DropDownList

0

"How to use option group with DropDownList" by CMSN Software Tutorials, shows you how to integrate option group in asp.net DropDownList. Default functionality of asp.net DropDownList doesn't support for option groups. So we thought to implement custom server control for supporting option group

Following sample show you the way of implementing custom server control to support option group with asp.net DropDownList.  We are inheriting asp.net DropDownList in to custom server control and then modify it to support option groups. In this custom control  we have introduced extra new custom property for option group field. So you can directly set that property when data binding.
//-----------------------------------------------------------------------
// <copyright file="CustomDropDownList.cs" company="CMSN Software">
//    Copyright © 2011  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
namespace CMSN.Software.Tutorials.HowToUseOptionGroupWithDropDownList
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
 
    /// <summary>
    /// custom dropdown list for support option groups
    /// </summary>
    [DefaultProperty("OptionGroupDataField")]
    [ToolboxData("<{0}:CustomDropDownList runat=server></{0}:CustomDropDownList>")]
    public class CustomDropDownList : DropDownList
    {
        /// <summary>
        /// Gets or sets the data option group field.
        /// </summary>
        /// <value>
        /// The data option group field.
        /// </value>
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DataOptionGroupField
        {
            get
            {
                string dataOptionGroupField = (string)ViewState["OptionGroupDataField"];
                return (dataOptionGroupField == null) ? string.Empty : dataOptionGroupField;
            }
 
            set
            {
                ViewState["OptionGroupDataField"] = value;
            }
        }
 
        /// <summary>
        /// Renders the items in the <see cref="T:System.Web.UI.WebControls.ListControl"/> control.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream used to write content to a Web page.</param>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (this.Items.Count > 0)
            {
                bool selected = false;
                Dictionary<stringList<ListItem>> optionGroupsCollection = this.OptionGroupsCollection();
                foreach (string optionGroup in optionGroupsCollection.Keys)
                {
                    writer.WriteBeginTag("optgroup");
                    writer.WriteAttribute("label", optionGroup);
                    writer.Write('>');
                    writer.WriteLine();
                    foreach (ListItem item in optionGroupsCollection[optionGroup])
                    {
                        writer.WriteBeginTag("option");
                        if (item.Selected)
                        {
                            if (selected)
                            {
                                this.VerifyMultiSelect();
                            }
 
                            selected = true;
                            writer.WriteAttribute("selected""selected");
                        }
 
                        writer.WriteAttribute("value", item.Value, true);
 
                        if (item.Attributes.Count > 0)
                        {
                            item.Attributes.Render(writer);
                        }
 
                        if (this.Page != null)
                        {
                            this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
                        }
 
                        writer.Write('>');
                        HttpUtility.HtmlEncode(item.Text, writer);
                        writer.WriteEndTag("option");
                        writer.WriteLine();
                    }
                }
 
                writer.WriteEndTag("optgroup");
            }
        }
 
        /// <summary>
        /// Option groups collection.
        /// </summary>
        /// <returns>Option groups collection</returns>
        private Dictionary<stringList<ListItem>> OptionGroupsCollection()
        {
            // temporary storage to options based on option group. inside this, 
            // all options will be grouped based on the option group value.
            Dictionary<stringList<ListItem>> optionGroupsCollection = new Dictionary<stringList<ListItem>>();
            string lastOptionGroup = string.Empty;
            int i = 0;
            List<ListItem> optionGroupMembers = null;
 
            // loop through the data source
            if (DataSource != null)
            {
                foreach (var dataRow in this.DataSource as IEnumerable)
                {
                    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(dataRow);
                    PropertyDescriptor propertyDescriptor = propertyDescriptorCollection.Find(this.DataOptionGroupField, true);
                    ListItem item = this.Items[i];
                    if (item.Enabled)
                    {
                        if (lastOptionGroup != propertyDescriptor.GetValue(dataRow).ToString())
                        {
                            lastOptionGroup = propertyDescriptor.GetValue(dataRow).ToString();
                            if (optionGroupsCollection.ContainsKey(lastOptionGroup))
                            {
                                optionGroupMembers = (List<ListItem>)optionGroupsCollection[lastOptionGroup];
                            }
                            else
                            {
                                optionGroupMembers = new List<ListItem>();
                            }
                        }
 
                        optionGroupMembers.Add(item);
 
                        if (optionGroupsCollection.ContainsKey(lastOptionGroup))
                        {
                            optionGroupsCollection[lastOptionGroup] = optionGroupMembers;
                        }
                        else
                        {
                            optionGroupsCollection.Add(lastOptionGroup, optionGroupMembers);
                        }
                    }
 
                    i++;
                }
            }
            return optionGroupsCollection;
        }
    }
}

In above code we are directly accessing the new custom property and then group all options based on the new property value by looping through the data source. Next step is creating the select box using above created option group collection. for that we override RenderContents event and create the select box using above created option group collection.

Following sample show you how to use our custom server control..
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OptionGroupWithDropDownList.aspx.cs"
    Inherits="HowToUseOptionGroupWithDropDownList.OptionGroupWithDropDownList" %>
 
<%@ Register Assembly="HowToUseOptionGroupWithDropDownList" Namespace="CMSN.Software.Tutorials.HowToUseOptionGroupWithDropDownList"
    TagPrefix="cmsn" %>
<!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>
        <cmsn:CustomDropDownList ID="DropDownWithOptionGroup" runat="server">
        </cmsn:CustomDropDownList>
    </div>
    </form>
</body>
</html>

Here only thing we need to do is, just drag and drop the new control to the page.

//-----------------------------------------------------------------------
// <copyright file="OptionGroupWithDropDownList.aspx.cs" company="CMSN Software">
//    Copyright © 2011  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
namespace HowToUseOptionGroupWithDropDownList
{
    using System;
    using System.Data;
    using System.Globalization;
 
    /// <summary>
    /// usage of custome dropdown list
    /// </summary>
    public partial class OptionGroupWithDropDownList : System.Web.UI.Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DropDownWithOptionGroup.DataSource = SampleData().Tables[0].DefaultView;
            this.DropDownWithOptionGroup.DataTextField = "FirstColumn";
            this.DropDownWithOptionGroup.DataValueField = "SecondColumn";
            this.DropDownWithOptionGroup.DataOptionGroupField = "ThirdColumn";
            this.DropDownWithOptionGroup.DataBind();
        }
 
        /// <summary>
        /// Sample data.
        /// </summary>
        /// <returns>data set with sample data</returns>
        private static DataSet SampleData()
        {
            DataSet sampleDataSet = new DataSet();
            sampleDataSet.Locale = CultureInfo.InvariantCulture;
            DataTable sampleDataTable = sampleDataSet.Tables.Add("SampleData");
 
            sampleDataTable.Columns.Add("FirstColumn"typeof(string));
            sampleDataTable.Columns.Add("SecondColumn"typeof(string));
            sampleDataTable.Columns.Add("ThirdColumn"typeof(string));
            DataRow sampleDataRow;
            for (int i = 1; i <= 49; i++)
            {
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow["FirstColumn"] = "Cell1: " + i;
                sampleDataRow["SecondColumn"] = "Cell2: " + i;
                sampleDataRow["ThirdColumn"] = "Cell3: " + i.ToString(CultureInfo.InvariantCulture).Substring(0, 1);
                sampleDataTable.Rows.Add(sampleDataRow);
            }
 
            return sampleDataSet;
        }
    }
}

here we need to mention DataOptionGroupField when data binding.

Download tutorial

0 comments:

Post a Comment