將對象綁定到窗體或將窗體數據賦值給對象(B/S、C/S)

B/S模式:

/*
版權信息:版權所有(C) 2007 IntelligenceSoft Corporation
作    者:ruijc
完成日期:2007-04-11
內容摘要:進行實體對象和頁面控件綁定類。

*/
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// 將對象綁定到窗口
/// </summary>
public class PageDataBinding
{
    /// <summary>
    /// 綁定對象到指定的容器
    /// </summary>
    /// <param name="obj">對象</param>
    /// <param name="container">容器</param>
    public static void BindObjectToControls(object obj, Control container)
    {
        if (obj == null) return;

        // 取得實體對象屬性
        Type objType = obj.GetType();
        PropertyInfo[] objPropertiesArray = objType.GetProperties();
        foreach (PropertyInfo objProperty in objPropertiesArray)
        {

            Control control = container.FindControl(objProperty.Name);
            if (control == null) continue;

            // ListControls控件類型 (DropDownList, CheckBoxList, RadioButtonList)
            if (control is ListControl)
            {
                ListControl listControl = (ListControl)control;
                string propertyValue = objProperty.GetValue(obj, null).ToString();
                ListItem listItem = listControl.Items.FindByValue(propertyValue);
                foreach (ListItem lItem in listControl.Items)
                {
                    lItem.Selected = false;
                }
                if (listItem != null) listItem.Selected = true;
            }
            else
            {
                SetControlValue(obj, objProperty, control);
            }
        }
    }

    /// <summary>
    /// 對控件屬性設置值
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="objProperty"></param>
    /// <param name="control"></param>
    private static void SetControlValue(object obj, PropertyInfo objProperty, Control control)
    {
        Type controlType = control.GetType();
        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

        bool success = false;
        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(Boolean));

        if (!success)
            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));

        if (!success)
            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

        if (!success)
            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

        if (!success)
            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "DataSource", typeof(Object));
    }


    /// <summary>
    /// 查找控件屬性並設置,要求控件ID命名必須與實體類屬性同名 
    /// </summary>
    /// <param name="obj">對象</param>
    /// <param name="objProperty">對象屬性</param>
    /// <param name="control">與對象屬性匹配的控件</param>
    /// <param name="controlPropertiesArray">控件屬性數組</param>
    /// <param name="propertyName">屬性名</param>
    /// <param name="type">類型</param>
    /// <returns>是否找到</returns>
    private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
    {
        foreach (PropertyInfo controlProperty in controlPropertiesArray)
        {
            if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
            {
                if (objProperty.PropertyType == typeof(Guid))
                {
                    GuidConverter guidConverter = new GuidConverter();
                    controlProperty.SetValue(control, guidConverter.ConvertTo(objProperty.GetValue(obj, null), type), null);
                    return true;
                }

                if (type == typeof(Object))
                {
                    type = objProperty.PropertyType;
                }

                controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 將值綁定到對象
    /// </summary>
    /// <param name="obj">對象</param>
    /// <param name="container">控件容器</param>
    public static void BindControlsToObject(object obj, Control container)
    {
        if (obj == null) return;

        Type objType = obj.GetType();
        PropertyInfo[] objPropertiesArray = objType.GetProperties();

        foreach (PropertyInfo objProperty in objPropertiesArray)
        {

            Control control = container.FindControl(objProperty.Name);
            if (control == null) continue;
            if (control is ListControl)
            {
                ListControl listControl = (ListControl)control;
                if (listControl.SelectedItem != null)
                    objProperty.SetValue(obj, Convert.ChangeType(listControl.SelectedItem.Value, objProperty.PropertyType), null);
            }
            else
            {
                GetControlValue(obj, objProperty, control);
            }
        }
    }

    private static void GetControlValue(object obj, PropertyInfo objProperty, Control control)
    {
        // 取得控件屬性
        Type controlType = control.GetType();
        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

        bool success = false;

        success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(Boolean));

        if (!success)
            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));

        if (!success)
            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

        if (!success)
            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

    }

    private static bool FindAndGetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
    {
        // 在整個控件屬性中進行迭代
        foreach (PropertyInfo controlProperty in controlPropertiesArray)
        {
            // 檢查匹配的名稱和類型
            if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
            {
                // 將控件的屬性設置爲
                // 業務對象屬性值
                try
                {
                    if (objProperty.PropertyType == typeof(Guid))
                    {
                        GuidConverter guidConverter = new GuidConverter();
                        objProperty.SetValue(obj, guidConverter.ConvertFrom(controlProperty.GetValue(control, null)), null);
                        //緩存控件屬性
                        return true;
                    }
                    if (objProperty.PropertyType.Name.Contains("Nullable"))
                    {
                        NullableConverter nullable = new NullableConverter(objProperty.PropertyType);
                        objProperty.SetValue(obj, nullable.ConvertFrom(controlProperty.GetValue(control, null)), null);
                    }
                    else
                    {
                        objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
                    }
                    return true;
                }
                catch
                {
                    // 無法將來自窗體控件 
                    // 的數據轉換爲業務對象屬性值 
                    return false;
                }
            }
        }
        return false;
    }
}
C/S模式:

    /// <summary>
    /// 進行實體對象和窗體控件綁定類
    /// </summary>
    public static class BindingMethod
    {
        /// <summary>
        /// 綁定對象到指定的容器
        /// </summary>
        /// <param name="obj">對象</param>
        /// <param name="container">容器</param>
        public static void BindObjectToControls(this Control container,object obj)
        {
            if (obj == null) return;

            // 取得實體對象屬性
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();
            foreach (PropertyInfo objProperty in objPropertiesArray)
            {

                Control control = container.Controls[objProperty.Name];
                if (control == null) continue;

                if (control is DateTimePicker)
                {
                    DateTimePicker dateTimePicker = (DateTimePicker)control;
                    dateTimePicker.Value = (DateTime)objProperty.GetValue(obj, null);
                }

                // ListControls控件類型 (DropDownList, CheckBoxList, RadioButtonList)
                if (control is ListControl)
                {
                    ListControl listControl = (ListControl)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    listControl.Text = propertyValue;
                }
                else
                {
                    SetControlValue(obj, objProperty, control);
                }
            }
        }

        /// <summary>
        /// 綁定datagridview值到list裏
        /// </summary>
        /// <param name="dgv">datagridview</param>
        /// <param name="lst">list</param>
        public static void BindGridViewToList<T>(this DataGridView dgv, List<T> lst) where T:new()
        { 
            if (lst == null) return;
            
            // 取得實體對象屬性
            try
            {
                Type objType = typeof(T);
               
                PropertyInfo[] objPropertiesArray = objType.GetProperties();
                foreach (DataGridViewRow rows in dgv.Rows)
                {
                    T entity = new T();
                    foreach (DataGridViewColumn col in dgv.Columns)
                    {
                        object result = dgv.Rows[rows.Index].Cells[col.Index].Value; 
                        var objProperty = (from item in objPropertiesArray
                                    where item.Name == col.DataPropertyName
                                    select item).SingleOrDefault();
                        if (objProperty == null) continue;
                        dgv.AllowUserToAddRows = false;

                        if (objProperty.PropertyType.Name.Contains("Nullable"))
                        {
                            NullableConverter nullable = new NullableConverter(objProperty.PropertyType);
                            //nullable.ConvertTo(result, typeof(InstanceDescriptor));

                            //objProperty.SetValue(entity, HackType(result, objProperty.PropertyType), null);
                            //objProperty.SetValue(entity, nullable.ConvertFrom(result), null);
                            if (result == null) continue;
                            if (nullable.UnderlyingType == typeof(Guid))
                            {
                                Guid newGuid = Guid.Parse(result.ToString().Trim());
                                objProperty.SetValue(entity, Convert.ChangeType(newGuid, nullable.UnderlyingType), null);
                            }
                            else
                            {
                                objProperty.SetValue(entity, Convert.ChangeType(result, nullable.UnderlyingType), null);
                            }
                        }
                        else
                        {
                            if (result == null) continue;
                            if (objProperty.PropertyType == typeof(Guid))
                            {
                                objProperty.SetValue(entity, Guid.Parse(result.ToString()), null);
                            }
                            else
                            {
                                objProperty.SetValue(entity, Convert.ChangeType(result, objProperty.PropertyType), null);
                            }
                        }
                    }
                    lst.Add(entity);
                }
             
            }
            catch (Exception ex)
            {
                MessageBox.Show("有錯"+ex.ToString());
            }
        }

        private static object HackType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable)))
            {
                if (value == null)
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            return Convert.ChangeType(value, conversionType);
        }

        /// <summary>
        /// 將值綁定到對象
        /// </summary>
        /// <param name="obj">對象</param>
        /// <param name="container">控件容器</param>
        public static void BindControlsToObject(this Control container, object obj)
        {
            if (obj == null) return;

            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();

            foreach (PropertyInfo objProperty in objPropertiesArray)
            {

                Control control = container.Controls[objProperty.Name];
                if (control == null) continue;
                if (control is ListControl)
                {
                    ListControl listControl = (ListControl)control;
                    if (listControl.SelectedValue != null)
                        objProperty.SetValue(obj, Convert.ChangeType(listControl.SelectedValue, objProperty.PropertyType), null);
                }
                else
                {
                    GetControlValue(obj, objProperty, control);
                }
            }
        }

        #region 私有方法
        /// <summary>
        /// 對控件屬性設置值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="objProperty"></param>
        /// <param name="control"></param>
        private static void SetControlValue(object obj, PropertyInfo objProperty, Control control)
        {
            Type controlType = control.GetType();
            PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

            bool success = false;
            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(Boolean));

            if (!success)
                success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(DateTime));

            if (!success)
                success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

            if (!success)
                success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

            if (!success)
                success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "DataSource", typeof(Object));
        }


        /// <summary>
        /// 查找控件屬性並設置,要求控件ID命名必須與實體類屬性同名 
        /// </summary>
        /// <param name="obj">對象</param>
        /// <param name="objProperty">對象屬性</param>
        /// <param name="control">與對象屬性匹配的控件</param>
        /// <param name="controlPropertiesArray">控件屬性數組</param>
        /// <param name="propertyName">屬性名</param>
        /// <param name="type">類型</param>
        /// <returns>是否找到</returns>
        private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    if (objProperty.PropertyType == typeof(Guid))
                    {
                        GuidConverter guidConverter = new GuidConverter();
                        controlProperty.SetValue(control, guidConverter.ConvertTo(objProperty.GetValue(obj, null), type), null);
                        return true;
                    }
                    if (objProperty.PropertyType.Name.Contains("Nullable"))
                    {
                        NullableConverter nullable = new NullableConverter(objProperty.PropertyType);
                        controlProperty.SetValue(control, nullable.ConvertTo(objProperty.GetValue(obj, null), type), null);
                        return true;
                    }

                    if (type == typeof(Object))
                    {
                        type = objProperty.PropertyType;
                    }

                    if (objProperty.GetValue(obj, null)==null)
                        continue;

                    controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
                    return true;
                }
            }
            return false;
        }

        private static void GetControlValue(object obj, PropertyInfo objProperty, Control control)
        {
            // 取得控件屬性
            Type controlType = control.GetType();
            PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

            bool success = false;

            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(Boolean));

            if (!success)
                success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));

            if (!success)
                success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

            if (!success)
                success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

        }

        private static bool FindAndGetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            // 在整個控件屬性中進行迭代
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                // 檢查匹配的名稱和類型
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    // 將控件的屬性設置爲
                    // 業務對象屬性值
                    try
                    {
                        if (objProperty.PropertyType == typeof(Guid))
                        {
                            GuidConverter guidConverter = new GuidConverter();
                            objProperty.SetValue(obj, guidConverter.ConvertFrom(controlProperty.GetValue(control, null)), null);
                            //緩存控件屬性
                            return true;
                        }
                        if (objProperty.PropertyType.Name.Contains("Nullable"))
                        {
                            NullableConverter nullable = new NullableConverter(objProperty.PropertyType);
                            objProperty.SetValue(obj, nullable.ConvertFrom(controlProperty.GetValue(control, null)), null);
                        }
                        else
                        {
                            objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
                        }
                        return true;
                    }
                    catch
                    {
                        // 無法將來自窗體控件 
                        // 的數據轉換爲業務對象屬性值 
                        return false;
                    }
                }
            }
            return false;
        }
        #endregion
    }



發佈了25 篇原創文章 · 獲贊 6 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章