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

Логин

Email:
  Пароль:

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

Поиск

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

Книги по теме

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

Исходник

Автор:

Temych

 
Название:

RequiredFieldValidator и SummaryValidator для WinForms

Дата: 24 January 2005
Описание: Огромное спасибо W@ndERR за победу над дизайн-тайм поддержкой компонентов. 
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=120]RequiredFieldValidator и SummaryValidator для WinForms[/CODEPOST]
Оценка: Проголосовало 5 посетителей, средняя оценка 4.60
Оценить:
  1 using System.Windows.Forms;
  2 
  3 namespace HostingLtd.DigitalHotel.UI.Components
  4 {
  5 	/// <summary>
  6 	/// IValidator
  7 	/// </summary>
  8 	public interface IValidator
  9 	{
 10 		bool IsValid
 11 		{
 12 			get;
 13 		}
 14 
 15 		Control TargetControl
 16 		{
 17 			get;
 18 			set;
 19 		}
 20 	}
 21 }
 22 
 23 using HostingLtd.DigitalHotel.UI.Components.Design;
 24 using System;
 25 using System.ComponentModel;
 26 using System.Drawing;
 27 using System.Reflection;
 28 using System.Windows.Forms;
 29 
 30 using HostingLtd.DigitalHotel.UI.Components.Design;
 31 
 32 namespace HostingLtd.DigitalHotel.UI.Components
 33 {
 34 	/// <summary>
 35 	/// RequiredFieldValidator.
 36 	/// </summary>
 37 	public class RequiredFieldValidator : Component, IValidator
 38 	{
 39 		#region Private fields 
 40 
 41 		private Container components = null;
 42 		//private static readonly log4net.ILog Logger = 
 43 		//	log4net.LogManager.GetLogger( typeof(RequiredFieldValidator) );	
 44 
 45 		private Control _targetControl;
 46 		private ContainerControl _containerControl;
 47 		private string _targetProperty;
 48 		private string _errorText;
 49 		private ErrorProvider _errorProvider;
 50 
 51 		#endregion Private fields 
 52 
 53 
 54 		#region Private properties 
 55 
 56 		private ContainerControl ContainerControl
 57 		{
 58 			get
 59 			{
 60 				Control control = TargetControl.Parent;
 61 
 62 				while(control != null)
 63 				{
 64 					if (control is ContainerControl)
 65 					{
 66 						return (ContainerControl)control;
 67 					}
 68 
 69 					control = control.Parent;
 70 				}
 71 
 72 				return null;
 73 			}
 74 		}
 75 
 76 		#endregion Private properties 
 77 
 78 
 79 		#region Public properties 
 80 
 81 		[Browsable(true)]
 82 		[Category("Behavior")]
 83 		[TypeConverter(typeof(TargetPropertyConverter))]
 84 		public string TargetProperty
 85 		{
 86 			get
 87 			{
 88 				return _targetProperty;
 89 			}
 90 			set
 91 			{
 92 				_targetProperty = value;
 93 			}
 94 		}
 95 
 96 		[Browsable(true)]
 97 		[Category("Appearance")]
 98 		[Localizable(true)]
 99 		public string ErrorText
100 		{
101 			get
102 			{
103 				if ((_errorText == null) || (_errorText == string.Empty))
104 				{
105 					return " ";
106 				}
107 
108 				return _errorText;
109 			}
110 			set
111 			{
112 				_errorText = value;
113 			}
114 		}
115 
116 		[Browsable(true)]
117 		[Category("Appearance")]
118 		[Localizable(true)]
119 		public Icon Icon
120 		{
121 			get
122 			{
123 				return _errorProvider.Icon;
124 			}
125 			set
126 			{
127 				_errorProvider.Icon = value;
128 			}
129 		}
130 
131 		[Browsable(true)]
132 		[Category("Appearance")]
133 		[Localizable(false)]
134 		public int BlinkRate
135 		{
136 			get
137 			{
138 				return _errorProvider.BlinkRate;
139 			}
140 			set
141 			{
142 				_errorProvider.BlinkRate = value;
143 			}
144 		}
145 
146 		[Browsable(true)]
147 		[Category("Appearance")]
148 		[Localizable(false)]
149 		public ErrorBlinkStyle BlinkStyle
150 		{
151 			get
152 			{
153 				return _errorProvider.BlinkStyle;
154 			}
155 			set
156 			{
157 				_errorProvider.BlinkStyle = value;
158 			}
159 		}
160 
161 		#endregion Public properties 
162 
163 
164 		#region Constructors 
165 
166 		public RequiredFieldValidator(IContainer container)
167 		{
168 			container.Add(this);
169 			InitializeComponent();
170 			CustomizeComponent();
171 		}
172 
173 		public RequiredFieldValidator()
174 		{
175 			InitializeComponent();
176 			CustomizeComponent();
177 		}
178 
179 		#endregion Constructors 
180 
181 
182 		#region Private methods 
183 
184 
185 		#region Component Designer generated code
186 
187 		private void InitializeComponent()
188 		{
189 			components = new System.ComponentModel.Container();
190 		}
191 
192 		#endregion
193 
194 
195 		#region Component Designer generated code custom extension 
196 
197 		private void CustomizeComponent()
198 		{
199 			_errorProvider = new ErrorProvider();
200 		}
201 
202 		#endregion Component Designer generated code custom extension 
203 
204 
205 		private void _controlToValidate_Validated(object sender, EventArgs e)
206 		{
207 			Validate();
208 		}
209 
210 		private void SetTargetProperyDevaultValue()
211 		{
212 			if (TargetControl is TextBox)
213 			{
214 				TargetProperty = "Text";
215 				return;
216 			}
217 
218 			if (TargetControl is ComboBox)
219 			{
220 				TargetProperty = "SelectedValue";
221 				return;
222 			}
223 
224 			TargetProperty = string.Empty;
225 		}
226 
227 		private bool Validate()
228 		{
229 			if ((TargetControl == null) || (!TargetControl.Enabled) || (!TargetControl.Visible))
230 			{
231 				return true;
232 			}
233 
234 			if ((TargetProperty == null) || (TargetProperty == string.Empty))
235 			{
236 				throw new InvalidOperationException("TargetProperty is not set");
237 			}
238 
239 			PropertyInfo targetProperty = TargetControl.GetType().GetProperty(TargetProperty);
240 			object propertyValue = targetProperty.GetValue(TargetControl, new object[0]);
241 
242 			_errorProvider.ContainerControl = ContainerControl;
243 
244 			if ((propertyValue == null) || ((propertyValue is string) && (((string)propertyValue).Trim() == string.Empty)))
245 			{
246 				_errorProvider.SetError(TargetControl, ErrorText);
247 				return false;
248 			}
249 			else
250 			{
251 				_errorProvider.SetError(TargetControl, string.Empty);
252 				return true;
253 			}
254 		}
255 
256 		#endregion Private methods 
257 
258 
259 		#region Protected methods 
260 
261 		protected override void Dispose(bool disposing)
262 		{
263 			if (disposing)
264 			{
265 				if (components != null)
266 				{
267 					components.Dispose();
268 				}
269 			}
270 
271 			_errorProvider.Dispose();
272 
273 			base.Dispose(disposing);
274 		}
275 
276 		#endregion Protected methods 
277 
278 
279 		#region IValidator implementation 
280 
281 		[Browsable(false)]
282 		public bool IsValid
283 		{
284 			get
285 			{
286 				return Validate();
287 			}
288 		}
289 
290 		[Browsable(true)]
291 		[Category("Behavior")]
292 		[RefreshProperties(RefreshProperties.All)]
293 		public Control TargetControl
294 		{
295 			get
296 			{
297 				return _targetControl;
298 			}
299 			set
300 			{
301 				if (_targetControl == value)
302 				{
303 					return;
304 				}
305 
306 				if (_targetControl != null)
307 				{
308 					_targetControl.Validated -= new EventHandler(_controlToValidate_Validated);
309 				}
310 
311 				_targetControl = value;
312 
313 				if (_targetControl != null)
314 				{
315 					_targetControl.Validated += new EventHandler(_controlToValidate_Validated);
316 					SetTargetProperyDevaultValue();
317 				}
318 				else
319 				{
320 					TargetProperty = string.Empty;
321 				}
322 			}
323 		}
324 
325 		#endregion IValidator implementation 
326 	}
327 }
328 
329 using System;
330 using System.Collections;
331 using System.ComponentModel;
332 using System.ComponentModel.Design;
333 using System.Windows.Forms;
334 
335 namespace HostingLtd.DigitalHotel.UI.Components
336 {
337 	/// <summary>
338 	/// SummaryValidator
339 	/// </summary>
340 	[ProvideProperty("Inscribe", typeof(IValidator))]
341 	public class SummaryValidator : Component, IValidator, IExtenderProvider
342 	{
343 		#region Private fields 
344 
345 		//private static readonly log4net.ILog Logger = 
346 		//	log4net.LogManager.GetLogger( typeof(SummaryValidator) );	
347 
348 		private Container components = null;
349 		private ArrayList _validators;
350 		private bool _validateOnFormClosing;
351 		private ContainerControl _containerControl;
352 		private Form _parentForm;
353 
354 		#endregion Private fields 
355 
356 
357 		#region Constructors 
358 
359 		public SummaryValidator(IContainer container)
360 		{
361 			container.Add(this);
362 			InitializeComponent();
363 			CustomizeComponent();
364 		}
365 
366 		public SummaryValidator()
367 		{
368 			InitializeComponent();
369 			CustomizeComponent();
370 		}
371 
372 		#endregion Constructors 
373 
374 
375 		#region Private properties 
376 
377 		private Form ParentForm
378 		{
379 			get
380 			{
381 				return _parentForm;
382 			}
383 			set
384 			{
385 				if (_parentForm != null)
386 				{
387 					_parentForm.Closing -= new CancelEventHandler(_parentForm_Closing);
388 				}
389 
390 				_parentForm = value;
391 
392 				if (_parentForm != null)
393 				{
394 					_parentForm.Closing += new CancelEventHandler(_parentForm_Closing);
395 				}
396 			}
397 		}
398 
399 		#endregion Private properties 
400 
401 
402 		#region Public properties  
403 
404 		[Browsable(true)]
405 		[Category("Behavior")]
406 		[DefaultValue(true)]
407 		public bool ValidateOnFormClosing
408 		{
409 			get
410 			{
411 				return _validateOnFormClosing;
412 			}
413 			set
414 			{
415 				_validateOnFormClosing = value;
416 			}
417 		}
418 
419 		[Browsable(true)]
420 		[Category("Appearance")]
421 		public ContainerControl ContainerControl
422 		{
423 			get
424 			{
425 				return _containerControl;
426 			}
427 			set
428 			{
429 				if (_containerControl == value)
430 				{
431 					return;
432 				}
433 
434 				if ((_containerControl != null) && !(_containerControl is Form))
435 				{
436 					_containerControl.ParentChanged -= new EventHandler(_containerControl_ParentChanged);
437 				}
438 
439 				_containerControl = value;
440 
441 				if (_containerControl != null)
442 				{
443 					ParentForm = GetParentForm(_containerControl);
444 
445 					if (!(_containerControl is Form))
446 					{
447 						_containerControl.ParentChanged += new EventHandler(_containerControl_ParentChanged);
448 					}
449 				}
450 			}
451 		}
452 
453 		public override ISite Site
454 		{
455 			get
456 			{
457 				return base.Site;
458 			}
459 			set
460 			{
461 				base.Site = value;
462 
463 				if (value == null)
464 				{
465 					return;
466 				}
467 
468 				IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
469 
470 				if ((host == null) || !(host.RootComponent is ContainerControl))
471 				{
472 					return;
473 				}
474 
475 				this.ContainerControl = (ContainerControl)host.RootComponent;
476 			}
477 		}
478 
479 		#endregion Public properties  
480 
481 
482 		#region Private methods 
483 
484 
485 		#region Component Designer generated code
486 
487 		private void InitializeComponent()
488 		{
489 			components = new System.ComponentModel.Container();
490 		}
491 
492 		#endregion
493 
494 
495 		#region Component Designer generated code custom extension 
496 
497 		private void CustomizeComponent()
498 		{
499 			_validators = new ArrayList();
500 			_validateOnFormClosing = true;
501 		}
502 
503 		#endregion Component Designer generated code custom extension 
504 
505 
506 		private bool Validate()
507 		{
508 			bool atLeastOneNotValid = false;
509 
510 			foreach(IValidator item in _validators)
511 			{
512 				if (!item.IsValid)
513 				{
514 					atLeastOneNotValid = true;
515 				}
516 			}
517 
518 			return !atLeastOneNotValid;
519 		}
520 
521 		private void _parentForm_Closing(object sender, CancelEventArgs e)
522 		{
523 			if (!ValidateOnFormClosing)
524 			{
525 				return;
526 			}
527 
528 			e.Cancel = !IsValid;
529 		}
530 
531 		private void _containerControl_ParentChanged(object sender, EventArgs e)
532 		{
533 			ParentForm = GetParentForm(_containerControl);
534 		}
535 
536 		private Form GetParentForm(ContainerControl containerControl)
537 		{
538 			if (containerControl == null)
539 			{
540 				return null;
541 			}
542 
543 			if (containerControl is Form)
544 			{
545 				return (Form)containerControl;
546 			}
547 
548 			return containerControl.ParentForm;
549 		}
550 
551 		#endregion Private methods 
552 
553 
554 		#region Public methods 
555 
556 		public void SetInscribe(IValidator validator, bool value)
557 		{
558 			if (!value)
559 			{
560 				_validators.Remove(validator);
561 				return;
562 			}
563 
564 			_validators.Add(validator);
565 		}
566 
567 		[DefaultValue(false)]
568 		[Category("Behavior")]
569 		public bool GetInscribe(IValidator validator)
570 		{
571 			return _validators.Contains(validator);
572 		}
573 
574 		#endregion Public methods 
575 
576 
577 		#region IExtenderProvider implementation 
578 
579 		public bool CanExtend(object extendee)
580 		{
581 			if (extendee == this)
582 			{
583 				return false;
584 			}
585 
586 			return (extendee is IValidator);
587 		}
588 
589 		#endregion IExtenderProvider implementation 
590 
591 
592 		#region IValidator implementation 
593 
594 		[Browsable(false)]
595 		public bool IsValid
596 		{
597 			get
598 			{
599 				return Validate();
600 			}
601 		}
602 
603 		[Browsable(false)]
604 		public Control TargetControl
605 		{
606 			get
607 			{
608 				return null;
609 			}
610 			set
611 			{}
612 		}
613 
614 		#endregion IValidator implementation
615 	}
616 }
617 
618 
619 using System;
620 using System.Collections;
621 using System.ComponentModel;
622 using System.Reflection;
623 using System.Windows.Forms;
624 
625 namespace HostingLtd.DigitalHotel.UI.Components.Design
626 {
627 	/// <summary>
628 	/// RequiredFieldValidatorConverter.
629 	/// </summary>
630 	public class TargetPropertyConverter : System.ComponentModel.TypeConverter
631 	{
632 		#region Public properties 
633 
634 		public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
635 		{
636 			return true;
637 		}
638 		
639 		public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
640 		{
641 			Control controlToValidate = ( (RequiredFieldValidator)context.Instance).TargetControl;
642 			
643 			if (controlToValidate == null)
644 			{
645 				return new TypeConverter.StandardValuesCollection( new ArrayList() );
646 			}
647 
648 			ArrayList properties  = new ArrayList();
649 			
650 			foreach(PropertyInfo item in
651 				controlToValidate.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) )
652 			{
653 				properties.Add(item.Name);
654 			}
655 
656 			return new TypeConverter.StandardValuesCollection(properties);
657 		}
658 
659 		#endregion Public properties 
660 	}
661 }
662 
Вернуться к списку исходников в категории Winforms
 
Apartments for Rent

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