Rambler's Top100
Главная
Новости
Статьи
Форумы
Книги
Коды
Сообщество
Блоги
О нас
 

Логин

Email:
  Пароль:

Войти
Зарегистрироваться
Забыл пароль

Поиск

 Искать :
 
Вперед

Книги по теме

Искать:
в:
Порядок:

Исходник

Автор:

miksh

 
Название:

DropDownList c поддержкой OptGroup

Дата: 24 February 2005
Описание: Простое расширение DropDownList для поддержки группировки элементов с помощью тега OptGroup 
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=128]DropDownList c поддержкой OptGroup[/CODEPOST]
Оценка: Проголосовало 36 посетителей, средняя оценка 3.39
Оценить:
  1 using System;
  2 using System.Collections;
  3 using System.Web;
  4 using System.Web.UI;
  5 using System.Web.UI.WebControls;
  6 using System.ComponentModel;
  7 
  8 namespace MyCustomControls
  9 {
 10 	/// <summary>
 11 	/// Summary description for GroupDropDownList.
 12 	/// </summary>
 13 	[ToolboxData("<{0}:GroupDropDownList runat=server></{0}:GroupDropDownList>")]
 14 	public class GroupDropDownList : System.Web.UI.WebControls.DropDownList
 15 	{
 16 		/// <summary>
 17 		/// The field in the datasource which provides values for groups
 18 		/// </summary>
 19 		[DefaultValue(""), Category("Data")]
 20 		public virtual string DataGroupField
 21 		{
 22 			get
 23 			{
 24 				object obj = this.ViewState["DataGroupField"];
 25 				if (obj != null)
 26 				{
 27 					return (string) obj;
 28 				}
 29 				return string.Empty;
 30 			}
 31 			set
 32 			{
 33 				this.ViewState["DataGroupField"] = value;
 34 			}
 35 		}
 36  
 37 
 38 		/// <summary>
 39 		/// Render this control to the output parameter specified.
 40 		/// Based on the source code of the original DropDownList method
 41 		/// </summary>
 42 		/// <param name="output"> The HTML writer to write out to </param>
 43 		protected override void RenderContents(HtmlTextWriter writer)
 44 		{
 45 			ListItemCollection items = this.Items;
 46 			int itemCount = this.Items.Count;
 47 			string curGroup = String.Empty;
 48 			string itemGroup;
 49 			bool bSelected = false;
 50 
 51 			if (itemCount <= 0)
 52 			{
 53 				return;
 54 			}
 55 
 56 			for (int i = 0; i < itemCount; i++)
 57 			{
 58 				ListItem item = items[i];
 59 				itemGroup = (string)item.Attributes["DataGroupField"];
 60 				if (itemGroup != null && itemGroup != curGroup)
 61 				{
 62 					if (curGroup != String.Empty)
 63 					{
 64 						writer.WriteEndTag("optgroup");
 65 						writer.WriteLine();
 66 					}
 67 
 68 					curGroup = itemGroup;
 69 					writer.WriteBeginTag("optgroup");
 70 					writer.WriteAttribute("label", curGroup, true);
 71 					writer.Write('>');
 72 					writer.WriteLine();
 73 				}
 74 
 75 				writer.WriteBeginTag("option");
 76 				if (item.Selected)
 77 				{
 78 					if (bSelected)
 79 					{
 80 						throw new HttpException("Cant_Multiselect_In_DropDownList");
 81 					}
 82 					bSelected = true;
 83 					writer.WriteAttribute("selected", "selected", false);
 84 				}
 85 				writer.WriteAttribute("value", item.Value, true);
 86 				writer.Write('>');
 87 				HttpUtility.HtmlEncode(item.Text, writer);
 88 				writer.WriteEndTag("option");
 89 				writer.WriteLine();
 90 			}
 91 			if (curGroup != String.Empty)
 92 			{
 93 				writer.WriteEndTag("optgroup");
 94 				writer.WriteLine();
 95 			}
 96 		}
 97 
 98 		/// <summary>
 99 		/// Perform data binding logic that is associated with the control
100 		/// </summary>
101 		/// <param name="e">An EventArgs object that contains the event data</param>
102 		protected override void OnDataBinding(EventArgs e)
103 		{
104 			// Call base method to bind data
105 			base.OnDataBinding(e);
106 
107 			if (this.DataGroupField == String.Empty)
108 			{
109 				return;
110 			}
111 
112 			// For each Item add the attribute "DataGroupField" with value from the datasource
113 			IEnumerable dataSource = GetResolvedDataSource(this.DataSource, this.DataMember);
114 			if (dataSource != null)
115 			{
116 				ListItemCollection items = this.Items;
117 				int i = 0;
118 
119 				string groupField = this.DataGroupField;
120 				foreach (object obj in dataSource)
121 				{
122 					string groupFieldValue = DataBinder.GetPropertyValue(obj, groupField, null);
123 					ListItem item = items[i];
124 					item.Attributes.Add("DataGroupField", groupFieldValue);
125 					i++;
126 				}
127 			}
128 
129 		} 
130 
131 		/// <summary>
132 		/// This is copy of the internal ListControl method
133 		/// </summary>
134 		/// <param name="dataSource"></param>
135 		/// <param name="dataMember"></param>
136 		/// <returns></returns>
137 		private IEnumerable GetResolvedDataSource(object dataSource, string dataMember)
138 		{
139 			if (dataSource != null)
140 			{
141 				IListSource source1 = dataSource as IListSource;
142 				if (source1 != null)
143 				{
144 					IList list1 = source1.GetList();
145 					if (!source1.ContainsListCollection)
146 					{
147 						return list1;
148 					}
149 					if ((list1 != null) && (list1 is ITypedList))
150 					{
151 						ITypedList list2 = (ITypedList) list1;
152 						PropertyDescriptorCollection collection1 = list2.GetItemProperties(new PropertyDescriptor[0]);
153 						if ((collection1 == null) || (collection1.Count == 0))
154 						{
155 							throw new HttpException("ListSource_Without_DataMembers");
156 						}
157 						PropertyDescriptor descriptor1 = null;
158 						if ((dataMember == null) || (dataMember.Length == 0))
159 						{
160 							descriptor1 = collection1[0];
161 						}
162 						else
163 						{
164 							descriptor1 = collection1.Find(dataMember, true);
165 						}
166 						if (descriptor1 != null)
167 						{
168 							object obj1 = list1[0];
169 							object obj2 = descriptor1.GetValue(obj1);
170 							if ((obj2 != null) && (obj2 is IEnumerable))
171 							{
172 								return (IEnumerable) obj2;
173 							}
174 						}
175 						throw new HttpException("ListSource_Missing_DataMember");
176 					}
177 				}
178 				if (dataSource is IEnumerable)
179 				{
180 					return (IEnumerable) dataSource;
181 				}
182 			}
183 			return null;
184 		}
185 
186 	}
187 }
188 
Вернуться к списку исходников в категории Создание элементов управления
 
Apartments for Rent

Rambler's Top100
Рейтинг@Mail.ru
Идея: Dimon aka Manowar Программирование: Dimon aka Manowar Дизайн: Dan Lebedev
Хостинг от компании Parking.ru
Карта сайта