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

Логин

Email:
  Пароль:

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

Поиск

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

Книги по теме

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

Исходник

Автор:

Voennich

 
Название:

Custom DataGrid

Дата: 11 October 2002
Описание: Custom Column, CustomDataGrid etc  
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=13]Custom DataGrid[/CODEPOST]
Оценка: Проголосовало 23 посетителей, средняя оценка 4.43
Оценить:
  1 using System;
  2 using System.Collections;
  3 using System.Data;
  4 using System.Web.UI;
  5 using System.Web.UI.HtmlControls;
  6 using System.Web.UI.WebControls;
  7 
  8 namespace kcs.RegularTable
  9 {
 10 	public class HeaderDef
 11 	{
 12 		/// <summary>
 13 		/// Элемент - описатель заголовка таблицы
 14 		/// </summary>
 15 		private string _text;
 16 		private int _colspan = 0;
 17 		private int _rowspan = 0;
 18 		private Unit _width;
 19 		private Unit _height;
 20 		private TableItemStyle _style;
 21 		private bool _exists = true;
 22 		
 23 	#region Properties - доступ к Private свойствам
 24 		public string Text
 25 		{
 26 			get {return _text;}
 27 			set {_text = value;}
 28 		}
 29 		public TableItemStyle Style
 30 		{
 31 			get 
 32 			{
 33 				if ( _style == null)
 34 					_style = new TableItemStyle();
 35 				return _style;
 36 			}
 37 		}
 38 		public int ColSpan
 39 		{
 40 			get {return _colspan; }
 41 			set { if (value>0) _colspan = value; }
 42 		}
 43 		public int RowSpan
 44 		{
 45 			get {return _rowspan; }
 46 			set { if (value>0) _rowspan = value; }
 47 		}
 48 		public bool Exists
 49 		{
 50 			get { return _exists; }
 51 			set { _exists = value; }
 52 		}
 53 		public Unit Width
 54 		{
 55 			get {return _width; }
 56 			set { _width = value; }
 57 		}
 58 		public Unit Height
 59 		{
 60 			get {return _height; }
 61 			set { _height = value; }
 62 		}
 63 
 64 	#endregion
 65 		override public string ToString()
 66 		{
 67 			return "Header Text:"+_text;
 68 		}
 69 		
 70 		public TableHeaderCell ToTH()
 71 		{
 72 			TableHeaderCell th = new TableHeaderCell();
 73 			th.Text = this._text;
 74 			if (this._colspan>1)
 75 				th.ColumnSpan = this._colspan;
 76 			if (this._rowspan>1)
 77 				th.RowSpan = this._rowspan;
 78 			if (this._style!=null)
 79 				th.ControlStyle.CopyFrom(this._style);
 80 			if (this._exists)
 81 				return th;
 82 			else
 83 				return null;
 84 		}
 85 	}
 86 
 87 
 88 	public class HeaderDefCollection : ICollection
 89 	{
 90 		private HeaderDef[] _array;
 91 		private int _size;
 92 		private const int _MinStep =5;
 93 		
 94 		public HeaderDefCollection()
 95 		{
 96 			_array = new HeaderDef[_MinStep];
 97 			_size = 0;
 98 		}
 99 
100 	# region из ICollection 
101 		public virtual void CopyTo(Array array, int index)
102 		{
103 			throw new Exception("Sorry It doesn`t work");
104 		}
105 		public virtual int Count
106 		{
107 			get {return _size; }
108 		}
109 		public virtual bool IsSynchronized 
110 		{
111 			get { return false; } 
112 		}
113 		public virtual Object SyncRoot
114 		{
115 			get { return this; }
116 		}
117 		internal Object GetElement(int i)
118 		{
119 			if ((i>0) && (i<=_size)) 
120 				return _array[i];
121 			else
122 				return null;
123 		}
124 
125 		public virtual IEnumerator GetEnumerator()
126 		{
127 			return new HeaderDefEnumerator(this);
128 		}
129 
130 		class HeaderDefEnumerator : IEnumerator
131 		{
132 			private HeaderDefCollection _col;
133 			private int _index;
134 			private Object _current;
135 
136 			internal HeaderDefEnumerator( HeaderDefCollection hc )
137 			{
138 				_col = hc;
139 				_index = 0;
140 				_current = _col._array;
141 				if (_col._size == 0)
142 					_index = -1;
143 			}
144 
145 			public  bool MoveNext() 
146 			{
147 				if (_index < 0) 
148 				{  
149 					_current = _col._array;
150 					return false;
151 				}
152 				_current = _col.GetElement(_index);
153 				_index++;
154 
155 				if (_index == _col._size)
156 					_index = -1;
157 				return true;
158 			}
159 
160 			public void Reset() 
161 			{
162 
163 				if (_col._size == 0)
164 					_index = -1;
165 				else
166 					_index = 0;
167 
168 				_current = _col._array;
169 			}
170 
171 			public Object Current 
172 			{
173 				get 
174 				{
175 					if (_current == _col._array)
176 					{
177 						if (_index == 0)
178 							throw new InvalidOperationException("Invalid Operation");
179 						else
180 							throw new InvalidOperationException("Invalid operation");
181 					}
182 					return _current;
183 				}
184 			}
185 		}
186 	#endregion
187 
188 		public int Add(object obj)
189 		{
190 			HeaderDef hd = (HeaderDef) obj;
191 			HeaderDef[] newarray;
192 			int capacity;
193 			if( _size == _array.Length )
194 			{
195 				capacity = _array.Length + _MinStep;
196 				newarray = new HeaderDef[capacity];
197 				Array.Copy(_array,newarray,_size);
198 				_array = newarray;
199 			}
200 			_array[_size] = (HeaderDef)obj;
201 			_size++;
202 			return _size-1;
203 		}
204 		public Object this[int num]
205 		{
206 			get
207 			{
208 				if  ( (num>=0) && (num<_size) )
209 					return this._array[num];
210 				else
211 					return null;
212 			}
213 			set{}
214 		}
215 
216 	}
217 
218 
219 	public class  Colmn: System.Web.UI.WebControls.BoundColumn
220 	{
221 		/// <summary>
222 		/// Модифицированный BoundColumn
223 		/// </summary>
224 		private int _colspan = 0;
225 		private int _rowspan = 0;
226 		private Unit _width;
227 		private Unit _height;
228 		private HeaderDefCollection _headers;
229 		
230 
231 		public Colmn()
232 		{
233 			_headers = new HeaderDefCollection();
234 		}
235 		public bool HeaderExists(int num)
236 		{
237 			try
238 			{
239 				if ( (num < this._headers.Count) && (num >= 0) && (this._headers.Count > 0) )
240 					return ((HeaderDef)_headers[num]).Exists;
241 
242 				if (num == 0) 
243 					return true;
244 				return false;
245 			}
246 			catch(Exception e)
247 			{
248 				throw new Exception(" Error in Colmn.HeaderExists num = " + num + " headerCount = " + this._headers.Count, e);
249 			}
250 		}
251 
252 		public TableHeaderCell ToHeaderCell(int num)
253 		{
254 			if (num >= 0)
255 			{
256 				if( (num == 0) && (this.HeaderCount==0) )
257 				{// Создаем заголовок описанный в самом Colmn
258 					TableHeaderCell	th = new TableHeaderCell();
259 					th.Text	= base.HeaderText;
260 					if (base.HeaderStyle != null)
261 						th.ControlStyle.CopyFrom(base.HeaderStyle);
262 					if (this._colspan > 1)
263 						th.ColumnSpan =	this._colspan;
264 					if (this._rowspan > 1)
265 						th.RowSpan = this._rowspan;
266 					th.Width = this._width;
267 					return th;
268 				}
269 				else
270 				{
271 					if ((_headers.Count > num) && (num>= 0)) 
272 						return ((HeaderDef)_headers[num]).ToTH();
273 					else
274 						return null;
275 				}
276 			}
277 			else
278 				throw new Exception("Cannot make TableHeaderCell at Pos #" + num + " header.Count = ");//TODO _headers.Count
279 		}
280 
281 		public int HeaderCount
282 		{
283 			get	
284 			{
285 				if (this._headers!=null)
286 					return this._headers.Count;
287 				else 
288 					return 0;
289 			}
290 		}
291 	#region public Properties 
292 		public int ColSpan
293 		{
294 			get {return _colspan; }
295 			set { if (value > 0) _colspan = value; }
296 		}
297 		public int RowSpan
298 		{
299 			get {return _rowspan; }
300 			set { if (value > 0) _rowspan = value; }
301 		}
302 		public Unit Width
303 		{
304 			get {return _width; }
305 			set { _width = value; }
306 		}
307 		public Unit Height
308 		{
309 			get {return _height; }
310 			set { _height = value; }
311 		}
312 		public HeaderDefCollection headers
313 		{
314 			get {return _headers;}
315 			set {_headers = value;}
316 		}
317 
318 	#endregion
319 	}
320 
321 
322 	public class RegularTable : System.Web.UI.WebControls.DataGrid
323 	{
324 		/// <summary>
325 		/// Модифицированная DataGrid 
326 		/// </summary>
327 		public string TableBreaker;
328 		private int _headerRowCount;
329 		private int[] _pagenum;
330 
331 		public RegularTable()
332 		{
333 			_pagenum = new int[1];
334 			_pagenum[0] = 0;
335 			this.AutoGenerateColumns = false; // ибо нефиг 
336 		}
337 		
338 		private void AddColumnTo(Object oc, DataGridItem di, int pos)
339 		{
340 			Colmn c;
341 			TableHeaderCell th;
342 			DataGridColumn dc;
343 			if (oc.GetType() != typeof(kcs.RegularTable.Colmn)  )
344 			{
345 				if (pos == 0) // это стандартный DataGrid`овский столбец - можем поставить его только в первую строку 
346 				{
347 					dc = (DataGridColumn)oc;
348 					th = new TableHeaderCell();
349 					th.Text = ( (DataGridColumn)oc).HeaderText;
350 					if (dc.HeaderStyle != null)
351 						th.ControlStyle.CopyFrom( dc.HeaderStyle );
352 					th.RowSpan = _headerRowCount; // "обычный" столбец будем вытягивать на весь заголовок
353 					di.Controls.Add(th);
354 				}
355 			}
356 			else // а это наш Colmn
357 			{ 
358 				c = (Colmn)oc;
359 				if (c.HeaderExists( pos ))
360 					di.Controls.Add( ((Colmn)oc).ToHeaderCell( pos ) );
361 			}
362 		}
363 		public void CustomRender(HtmlTextWriter output)
364 		{
365 			int thRowCount = 0;// счетчик номера строки заголовка
366 			foreach(Control cc in Controls)
367 				if ( (cc.HasControls() ) && (this.ShowHeader ) )
368 				{
369 					#region добавляем недостающие строки
370 					try
371 					{
372 						for(int i =0; i < _headerRowCount - 1 ; i++ )
373 						{
374 							DataGridItem dgi = new DataGridItem(-1, 0, ListItemType.Header );
375 							cc.Controls.AddAt(i+1, dgi );
376 						}
377 					}
378 					catch(Exception e )
379 					{
380 						Page.Trace.Warn("_RegularTable : CustomRender","new DataGridItem", e);
381 					}
382 					#endregion
383 					foreach(DataGridItem di in cc.Controls ) 
384 					{
385 						if (di.ItemType == ListItemType.Header ) 
386 						{
387 							if(di.Cells.Count > 0 )
388 								di.Cells.Clear(); // очищаем строку заголовка от ячеек
389 							foreach(Object oc in Columns)
390 								AddColumnTo(oc, di, thRowCount);
391 							thRowCount++;
392 						}
393 					}
394 				}
395 
396 			base.Render(output);
397 		}
398 		protected override void Render(HtmlTextWriter output)
399 		{
400 			_headerRowCount = 1;
401 			foreach(Object oc in Columns)
402 			{
403 				if (oc.GetType() == typeof(kcs.RegularTable.Colmn) ) 
404 				{ // наш столбец ! 
405 					Colmn c = (Colmn)oc;
406 					if (_headerRowCount < c.HeaderCount)
407 						_headerRowCount = c.HeaderCount;
408 					if (_headerRowCount < c.RowSpan )
409 						_headerRowCount = c.RowSpan; 
410 				}
411 			}
412 
413 			if (_pagenum[0]==0)
414 			{
415 				CustomRender(output);
416 				return;
417 			}
418 			DataTable dt = (DataTable) base.DataSource;
419 
420 			if (dt!=null) 
421 			{
422 
423 				int LastRow;
424 				bool PrintFooter;
425 				PrintFooter = base.ShowFooter;
426 				LastRow = dt.Rows.Count;
427 				DataView dw;
428 				dw = dt.DefaultView;
429 				base.ShowFooter = false;
430 				for(int i = 0, cpCount = 0 ; i < LastRow; i += this.GetPageNum(cpCount), cpCount++)
431 				{
432 					//Page.Trace.Write("_RegularTable : Render","i = " + i + " cpCount=" + cpCount + " pagenum=" + this.GetPageNum(cpCount) );
433 					dw.RowFilter="(_counter>" + i + ") AND (_counter <= " + ( i + this.GetPageNum(cpCount) )+")";
434 					base.DataSource = dw;
435 					if (LastRow - i < this.GetPageNum(cpCount + 1) )
436 						base.ShowFooter = PrintFooter;
437 					base.DataBind();
438 					CustomRender(output);
439 					if (LastRow-i > this.GetPageNum(cpCount + 1) )
440 						output.Write(TableBreaker);
441 				}
442 			}
443 			else
444 			{
445 				//Page.Trace.Warn("_RegularTable : Render" , "DataTable not Found");
446 				throw new Exception("_RegularTable : Render DataTable not Found");
447 			}
448 
449 		}
450 
451 		#region операции с нумерацией страниц 
452 		public string PageNum
453 		{
454 			set
455 			{
456 				string [] tmpstr;
457 				tmpstr = value.Split(new char[]{','});
458 				_pagenum = new int[tmpstr.Length];
459 				for(int i = 0; i < tmpstr.Length; i++ )
460 				{
461 					int crezult;
462 					crezult = Convert.ToInt32(tmpstr[i]);
463 					if (crezult > 0)
464 						_pagenum[i] = crezult;
465 					else
466 						_pagenum[i] = 0;
467 				}
468 			}
469 		}
470 		private int GetPageNum(int num) 
471 		{
472 			if ( (num >= 0) && (num < _pagenum.Length) )
473 				return _pagenum[num];
474 			else
475 				return _pagenum[_pagenum.Length - 1];
476 		}
477 		#endregion
478 
479 		public override object DataSource
480 		{
481 			get { return base.DataSource ; }
482 
483 			set 
484 			{ 
485 				DataView tdw;
486 				DataTable tdt = null;
487 
488 				Page.Trace.Write("_RegularTable : DataSource"," " + value.GetType() );
489 				try
490 				{
491 					if (value.GetType() == typeof(System.Data.DataView) )
492 					{
493 						Page.Trace.Write("_RegularTable : DataSource"," Its DataView ! " );
494 						tdw = (DataView) value;
495 						tdt = tdw.Table;
496 					}
497 					if (value.GetType() == typeof(System.Data.DataTable) )
498 					{
499 						tdt = (DataTable) value;
500 						tdt = tdt; 
501 					}
502 					if (tdt != null)
503 					{
504 						DataColumn dc = new DataColumn();
505 						dc.ColumnName = "_counter";
506 						if (!tdt.Columns.Contains("_counter"))
507 							tdt.Columns.Add(dc);
508 						tdt.AcceptChanges();
509 						int i = 1;
510 						foreach(DataRow dr in tdt.Rows)
511 							dr["_counter"] = i++;
512 						base.DataSource = tdt;
513 					}
514 					else
515 					{
516 						Page.Trace.Warn("_RegularTable : DataBind", "Cannot undestand DataSource " + value.GetType() + " Use default");
517 						base.DataSource = value; 
518 					}
519 				}
520 				catch(Exception e)
521 				{
522 					Page.Trace.Warn("_RegularTable : DataBind", "copy Error",e);
523 				}
524 			}
525 		}
526 	}
527 }
Вернуться к списку исходников в категории DataGrid, DataList, Repeater
 
Наш Киев

Apartments for Rent

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