[C#] 프로퍼티 값을 세팅하자.
2014. 3. 26. 17:54ㆍCoders
개발하다가, 특정 컨트롤의 특정 프로퍼티 값을 일괄로 세팅해야 할 일이 생겼습니다.(사실은 ReadOnly 값이요.) 부모 컨트롤 부터 잡아서 하위 컨트롤들의 모두 뒤져서(Recursive하게) ReadOnly라는 프로퍼티가 있는 컨트롤이면 ReadOnly 값을 세팅해 주는 코드를 짜 봤습니다.
(더불어, 해당 컨트롤의 하위 컨트롤에 버튼이 있을 수도 있어서, 해당 컨트롤 class명에 "button" 이라는 이름이 들어가 있으면 Enabled 값 까지 세팅하도록 추가했습니다.)
이 소스의 핵심은, 다음 두 가지 입니다.
Recursive하게 하위 컨트롤 찾아 들어가기.
컨트롤의 프로퍼티를 찾아서 set 할 수 있으면 set 하기.
소스 나갑니다.
참, using... 요 정도는 필요하겠죠.
using System.Windows.Forms;
using System.Reflection;
/// <summary> /// 자식들의 ReadOnly를 세팅. /// </summary> /// <param name="control">해당하는 컨트롤</param> /// <param name="ReadOnly">리드온리 여부</param> public static void SetReadOnlyDescendant(Control control, bool ReadOnly) { if (control.Controls != null && control.Controls.Count > 0) { foreach (Control child in control.Controls) { SetReadOnlyDescendant(child, ReadOnly); } } try { SetControlProperty(control, "ReadOnly", ReadOnly); if (control.GetType().Name.ToLower().Contains("button")) { SetControlProperty(control, "Enabled", !ReadOnly); } } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } /// <summary> /// 해당 컨트롤에 해당 프로퍼티가 있으면 값을 세팅한다. /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="control">컨트롤</param> /// <param name="propertyName">프로퍼티명</param> /// <param name="newValue">세팅할 값</param> public static void SetControlProperty<T>(Control control, string propertyName, T newValue) { try { PropertyInfo propInfo = control.GetType().GetProperty(propertyName, typeof(T)); if (propInfo != null) { MethodInfo setMethod = propInfo.GetSetMethod(); if (setMethod != null) { setMethod.Invoke(control, new object[] { newValue }); } } } catch (System.Exception ex) { throw ex; } }
'Coders' 카테고리의 다른 글
끄적끄적 만들어 본 웹서비스 테스트 툴 (0) | 2014.04.16 |
---|---|
64비트 응용 프로그램은 변경할 수 없습니다. 그리고 훌륭한 회사 마인드 (0) | 2014.03.26 |
[C#] JSON -> DataTable 변환시 DBNull 문제 (0) | 2014.03.05 |