Tags

, ,

        /// <summary>
        /// 从DataGridViewRow中获取交易实体
        /// </summary>
        /// <param name="row">DataGirdViewRow</param>
        /// <returns>实体对象</returns>
        private MyEntity getTransFromDataGridViewRow(DataGridViewRow row)
        {
            MyEntity entity = new MyEntity();
            //一些常量

            foreach (DataGridViewColumn col in dataGridView.Columns)
            {
                string property = col.Name;
                entity .setPropertyValue(property, row.Cells[property].Value);
            }
            return entity;
        }

MyEntity实体对象类:

        /// <summary>
        /// 根据名称设置属性(支持可空)
        /// </summary>
        /// <param name="propertyName">属性名</param>
        /// <param name="propertySetValue">属性值</param>
        public void setPropertyValue(string propertyName, object propertySetValue)
        {
            object[] value;
            if (propertySetValue == null || Convert.IsDBNull(propertySetValue)) //是否为空
            {
                Debug.WriteLine("Warning: Try to set null to property: " + propertyName);
                value = new object[] { null };
            }
            else
            {
                value = new object[] { Convert.ChangeType(propertySetValue, propertySetValue.GetType()) };
            }
            try
            {
                this.GetType().InvokeMember(propertyName, BindingFlags.SetProperty,null, this, value);
            }
            catch
            {
                Debug.WriteLine("ERROR: Faill to set property:" + propertyName + "tWith Type:" + propertySetValue.GetType());
            }
        }

别忘了导入命名空间:

using System.Reflection;
using System.Diagnostics;