C#采用反射获取字段的名字和注释自动添加到表格显示和修改

这是一个关于创建自定义DataGridView控件的示例,该控件支持折叠和展开功能,用于显示和编辑嵌套的数据。控件使用反射动态加载数据,能够展示数据结构,并允许用户在表格中直接修改数据。同时,控件还实现了点击展开和收起节点的功能,以及粘贴数据到表格的操作。
摘要由CSDN通过智能技术生成

简介说明

为了方便数据显示和修改
采用反射获取字段的名字和注释
自动将字段添加到表格中
在表格中修改数据后可以直接保存到对象中

可以折叠和复制黏贴的表格

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace UI
{
    public class DataGridViewGroupCell : DataGridViewTextBoxCell
    {
        #region Variant

        /// <summary>  
        /// 标示的宽度  
        /// </summary>  
        const int PLUS_WIDTH = 24;

        /// <summary>  
        /// 标示的区域  
        /// </summary>  
        Rectangle groupPlusRect;

        #endregion

        #region Init

        public DataGridViewGroupCell()
        {
            groupLevel = 1;
        }

        #endregion

        #region Property

        int groupLevel;

        /// <summary>  
        /// 组级别(以1开始)  
        /// </summary>  
        public int GroupLevel
        {
            get { return groupLevel; }
            set { groupLevel = value; }
        }

        DataGridViewGroupCell parentCell;

        /// <summary>  
        /// 父节点  
        /// </summary>  
        public DataGridViewGroupCell ParentCell
        {
            get
            {
                return parentCell;
            }
            set
            {
                if (value == null)
                    throw new NullReferenceException("父节点不可为空");
                if (!(value is DataGridViewGroupCell))
                    throw new ArgumentException("父节点必须为 DataGridViewGroupCell 类型");

                parentCell = value;
                parentCell.AddChildCell(this);
            }
        }

        private bool collapsed;

        /// <summary>  
        /// 是否收起  
        /// </summary>  
        public bool Collapsed
        {
            get { return collapsed; }
        }

        private List<DataGridViewGroupCell> childCells = null;

        /// <summary>  
        /// 所有的子结点  
        /// </summary>  
        public DataGridViewGroupCell[] ChildCells
        {
            get
            {
                if (childCells == null)
                    return null;
                return childCells.ToArray();
            }
        }

        /// <summary>  
        /// 取得组标示(有+或-号的框)的区域  
        /// </summary>  
        public Rectangle GroupPlusRect
        {
            get
            {
                return groupPlusRect;
            }
        }

        bool bPaint = true;

        /// <summary>  
        /// 是否重绘  
        /// </summary>  
        public bool BPaint
        {
            get { return bPaint; }
            set { bPaint = value; }
        }

        #endregion

        #region 添加子节点

        /// <summary>  
        /// 添加子结点  
        /// </summary>  
        /// <param name="cell"></param>  
        /// <returns></returns>  
        public int AddChildCell(DataGridViewGroupCell cell)
        {
            return AddChildCellRange(new DataGridViewGroupCell[] { cell });
        }

        public int AddChildCellRange(DataGridViewGroupCell[] cells)
        {
            bool needRedraw = false;
            if (childCells == null)
            {
                //需要画一个加号  
                childCells = new List<DataGridViewGroupCell>();
                needRedraw = true;
            }
            foreach (DataGridViewGroupCell cell in cells)
            {
                childCells.Add(cell);
                cell.groupLevel = groupLevel + 1;
                cell.parentCell = this;
            }

            if (needRedraw)
            {
                DataGridView.InvalidateCell(this);
            }
            return childCells.Count;
        }

        #endregion

        #region 绘制节点

        protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            if (!bPaint)
            {
                base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
                return;
            }
            Pen gridPen = new Pen(DataGridView.GridColor);
            Brush bruBK = new SolidBrush(cellStyle.BackColor);
            int width = groupLevel * PLUS_WIDTH;
            Rectangle rectLeft = new Rectangle(cellBounds.Left, cellBounds.Top - 1, width, cellBounds.Height);
            cellBounds.X += width;
            cellBounds.Width -= width;
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            PaintGroupPlus(graphics, gridPen, bruBK, cellStyle, rectLeft, collapsed);

            gridPen.Dispose();
            gridPen = null;

            bruBK.Dispose();
            bruBK = null;
        }

        private void PaintGroupPlus(Graphics graphics, Pen gridPen, Brush bruBK, DataGridViewCellStyle cellStyle, Rectangle rectLeft, bool collapsed)
        {
            Pen pen = new Pen(DataGridView.GridColor, 1);
            pen.DashStyle = DashStyle.Dot;
            graphics.FillRectangle(bruBK, rectLeft);
            int left = rectLeft.Left + (groupLevel - 1) * PLUS_WIDTH;
            //画 Left, Top, Right 三根线  
            graphics.DrawLine(gridPen, left, rectLeft.Top, rectLeft.Right, rectLeft.Top);//上  
            graphics.DrawLine(gridPen, rectLeft.Right, rectLeft.Bottom, rectLeft.Left, rectLeft.Bottom);

            //最左边的一条线  
            graphics.DrawLine(gridPen, rectLeft.Left, rectLeft.Top, rectLeft.Right, rectLeft.Top);

            //如果是该级别的最后一个节点,则需要画一个底线,以便将整个组封闭起来  
            bool drawBottomLine = false;
            for (int i = 1; i < groupLevel; i++)
            {
                if (!ParentCell.IsLastCell(ParentCell.groupLevel))//上层不是最后一个节点  
                {
                    graphics.DrawLine(pen, rectLeft.Left + (i - 1) * PLUS_WIDTH + PLUS_WIDTH / 2, rectLeft.Top
                        , rectLeft.Left + (i - 1) * PLUS_WIDTH + PLUS_WIDTH / 2, rectLeft.Bottom);
                }
            }

            //如果有子结点, 则需要画一个方框, 里面有+号或-号  
            if (childCells != null && childCells.Count > 0)
            {
                groupPlusRect = new Rectangle((groupLevel - 1) * PLUS_WIDTH + rectLeft.Left + (PLUS_WIDTH - 12) / 2
                    , rectLeft.Top + (rectLeft.Height - 12) / 2, 12, 12);
                graphics.DrawRectangle(gridPen, groupPlusRect);

                graphics.DrawLine(Pens.Black, groupPlusRect.Left + 3, groupPlusRect.Top + groupPlusRect.Height / 2
                , groupPlusRect.Right - 3, groupPlusRect.Top + groupPlusRect.Height / 2);
                if (collapsed)
                {
                    graphics.DrawLine(Pens.Black, groupPlusRect.Left + groupPlusRect.Width / 2, groupPlusRect.Top + 3
                , groupPlusRect.Left + groupPlusRect.Width / 2, groupPlusRect.Bottom - 3);
                }
            }
            else
            {
                //横  
                graphics.DrawLine(pen, rectLeft.Left + (groupLevel - 1) * PLUS_WIDTH + PLUS_WIDTH / 2, rectLeft.Top + rectLeft.Height / 2
              , rectLeft.Left + (groupLevel - 1) * PLUS_WIDTH + PLUS_WIDTH, rectLeft.Top + rectLeft.Height / 2);

                //竖  
                if (!IsLastCell((groupLevel - 1)))
                {
                    graphics.DrawLine(pen, rectLeft.Left + (groupLevel - 1) * PLUS_WIDTH + PLUS_WIDTH / 2, rectLeft.Top
                        , rectLeft.Left + (groupLevel - 1) * PLUS_WIDTH + PLUS_WIDTH / 2, rectLeft.Bottom);
                }
                else
                    graphics.DrawLine(pen, (groupLevel - 1) * PLUS_WIDTH + rectLeft.Left + (PLUS_WIDTH - 8) / 2 + 4, rectLeft.Top + (rectLeft.Height - 8) / 2 - 6,
                        (groupLevel - 1) * PLUS_WIDTH + rectLeft.Left + (PLUS_WIDTH - 8) / 2 + 4, rectLeft.Top + (rectLeft.Height - 8) / 2 + 4);

            }
            pen.Dispose();
            pen = null;
        }

        #endregion

        #region 判断

        /// <summary>  
        /// 该节点是否为某一级节点的最后一个子结点  
        /// </summary>  
        /// <param name="level">节点层级</param>  
        /// <returns></returns>  
        private bool IsLastCell(int level)
        {
            int row = DataGridView.Rows.GetNextRow(RowIndex, DataGridViewElementStates.None);
            if (row == -1)
                return true;
            DataGridViewGroupCell cel = DataGridView.Rows[row].Cells[0] as DataGridViewGroupCell;
            return (cel.GroupLevel == level);
        }

        #endregion

        #region 点击 Cell

        protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
        {
            Rectangle rect = DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, false);
            Point pt = new Point(rect.Left + e.Location.X, rect.Top + e.Location.Y);
            if (groupPlusRect.Contains(pt))
            {
                if (collapsed)
                {
                    Expand();
                }
                else
                {
                    Collapse();
                }
            }
            base.OnMouseDown(e);
        }
        public void UpdataShowChild()
        {
            if (collapsed)
            {
                Expand();
            }
            else
            {
                Collapse();
            }
        }
        #endregion

        #region 展开/收起节点

        /// <summary>  
        /// 展开节点  
        /// </summary>  
        public void Expand()
        {
            if (parentCell != null)
            {
                parentCell.CollapseAll();
            }
            collapsed = false;
            ShowChild(true);
            base.DataGridView.InvalidateCell(this);
        }

        private void ShowChild(bool show)
        {
            if (childCells == null)
                return;
            foreach (DataGridViewGroupCell cel in childCells)
            {
                if (cel.RowIndex == -1)
                {
                    continue;
                }

                DataGridView.Rows[cel.RowIndex].Visible = show;
                if (!cel.collapsed)
                    cel.ShowChild(show);
            }
        }

        /// <summary>  
        /// 收起节点  
        /// </summary>  
        public void Collapse()
        {
            collapsed = true;
            ShowChild(false);
            base.DataGridView.InvalidateCell(this);
        }

        /// <summary>  
        /// 展开节点及子结点  
        /// </summary>  
        public void ExpandAll()
        {
            if (childCells == null)
                return;
            foreach (DataGridViewGroupCell cel in childCells)
            {
                cel.ExpandAll();
            }
        }

        public void CollapseAll()
        {
            if (childCells == null)
                return;
            foreach (DataGridViewGroupCell cel in childCells)
            {
                cel.CollapseAll();
            }
        }

        #endregion
    }

    public class DataGridViewGroupColumn : DataGridViewTextBoxColumn
    {
        public DataGridViewGroupColumn()
        {
            CellTemplate = new DataGridViewGroupCell();
            ReadOnly = true;
        }

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                if ((value != null) && !(value is DataGridViewGroupCell))
                {
                    throw new InvalidCastException("Need System.Windows.Forms.DataGridViewGroupCell");
                }
                base.CellTemplate = value;
            }
        }
    }
    public class DefineDataGridView : DataGridView
    {
        bool showRowHeaderNumbers;
        /// 
        /// 是否显示行号 
        /// 
        /// [Description(“是否显示行号”), DefaultValue(true)]
        public bool ShowRowHeaderNumbers
        {
            get { return showRowHeaderNumbers; }
            set
            {
                if (showRowHeaderNumbers != value)
                    Invalidate();
                showRowHeaderNumbers = value;
            }
        }

        public DefineDataGridView()
        {
            showRowHeaderNumbers = true;
            this.RowHeadersWidth = 30;
            this.AllowUserToAddRows = false;
        }
    }
}

显示控件类

using MotionCtrl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UI
{
    public partial class DataGrideSysInfo : UserControl
    {
         public  delegate void ShowErrMsg(string str);
        public ShowErrMsg mShowErrMsg;
        public DataGrideSysInfo()
        {
            InitializeComponent();
        }
        public static string GetEnumDescrip(FieldInfo field)
        {

            DescriptionAttribute descAttr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descAttr == null)
                return string.Empty;
            return descAttr.Description;
        }
       public void ShowDataToGride(bool bLoad=true)
        {
            try
            {
                if(bLoad)
                {
                    var bok = NewSysInf.LoadSysInfCfg();

                    if(!bok)
                    {
                        MessageBox.Show("加载新参数数据失败");
                        return;
                    }
                }
                if (NewSysInf.NewParamse == null)
                    NewSysInf.NewParamse = new NewSysInf.NewParasAll();
                var obj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(NewSysInf.NewParamse));
                Type t = typeof(NewSysInf.NewParasAll);
                FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                var Properties= t.GetProperties();
                MyDge.Rows.Clear();
                int InsertClassId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
                MyDge.Rows[InsertClassId].Cells[0].Value = t.Name;
                MyDge.Rows[InsertClassId].Height = 50;
                MyDge.Rows[InsertClassId].Cells[0].Style.BackColor = Color.Gray;
                MyDge.Rows[InsertClassId].Cells[1].Value = "";
                MyDge.Rows[InsertClassId].Cells[2].Value = "";
                foreach (FieldInfo field in fields)
                {
                    var fieldTypeName = field.FieldType.Name;
                    var fieldName = field.Name;
                    int InsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
                    MyDge.Rows[InsertFieldId].Cells[0].Value = fieldName;
                    MyDge.Rows[InsertFieldId].Height = 45;
                    MyDge.Rows[InsertFieldId].Cells[0].Style.BackColor = Color.Gray;
                    MyDge.Rows[InsertFieldId].Cells[1].Value = GetEnumDescrip(field);
                    MyDge.Rows[InsertFieldId].Cells[2].Value = "";
                    ((DataGridViewGroupCell)MyDge.Rows[InsertClassId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]);


                    string StrDataobj = obj[field.Name].ToString();
                    Type temp = field.FieldType;
                    var mtype = field.FieldType;
                    object curobj = new object();

                    curobj = JsonConvert.DeserializeObject(StrDataobj, mtype);

                    if (curobj == null)
                    {
                        continue;
                    }

                    var mobj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(curobj));
                    FieldInfo[] mfields = temp.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    var mProperties = temp.GetProperties();
                    foreach (FieldInfo mfield in mfields)
                    {
                        bool bbool = mfield.FieldType.Name.Contains("ool");

                        int mInsertFieldId = 0;

                        if (bbool)
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewCheckBoxCell());
                        }
                        else
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewTextBoxCell());
                        }
                        MyDge.Rows[mInsertFieldId].Cells[0].Value = fieldName + "-" + mfield.Name;
                        MyDge.Rows[mInsertFieldId].Cells[1].Value = GetEnumDescrip(mfield);

                        if (bbool)
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2] = new DataGridViewCheckBoxCell() { Value = mobj[mfield.Name].ToString().Contains("rue") };

                        }
                        else
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2].Value = mobj[mfield.Name].ToString();
                        }
                        ((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[mInsertFieldId].Cells[0]);
                    }

                    foreach (var mfield in mProperties)
                    {
                        bool bbool = mfield.PropertyType.Name.Contains("ool");

                        int mInsertFieldId = 0;

                        if (bbool)
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewCheckBoxCell());
                        }
                        else
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewTextBoxCell());
                        }

                        MyDge.Rows[mInsertFieldId].Cells[0].Value = fieldName + "-" + mfield.Name;
                        MyDge.Rows[mInsertFieldId].Cells[1].Value = GetEnumDescrip(mfield);

                        if (bbool)
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2] = new DataGridViewCheckBoxCell() { Value = mobj[mfield.Name].ToString().Contains("rue") };

                        }
                        else
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2].Value = mobj[mfield.Name].ToString();
                        }
                    ((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[mInsertFieldId].Cells[0]);
                    }
                }

                          
                foreach (var field in Properties)
                {
                    var fieldTypeName = field.PropertyType.Name;
                    var fieldName = field.Name;
                    int InsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
                    MyDge.Rows[InsertFieldId].Cells[0].Value = fieldName;
                    MyDge.Rows[InsertFieldId].Height = 45;
                    MyDge.Rows[InsertFieldId].Cells[0].Style.BackColor = Color.Gray;
                    MyDge.Rows[InsertFieldId].Cells[1].Value = GetEnumDescrip(field);
                    MyDge.Rows[InsertFieldId].Cells[2].Value = "";
                    ((DataGridViewGroupCell)MyDge.Rows[InsertClassId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]);


                    string StrDataobj = obj[field.Name].ToString();
                    Type temp = field.PropertyType;
                    var mtype = field.PropertyType;
                    object curobj = new object();

                    curobj = JsonConvert.DeserializeObject(StrDataobj, mtype);

                    if (curobj == null)
                    {
                        continue;
                    }

                    var mobj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(curobj));
                    FieldInfo[] mfields = temp.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    var mProperties = temp.GetProperties();
                    foreach (FieldInfo mfield in mfields)
                    {
                        bool bbool = mfield.FieldType.Name.Contains("ool");

                        int mInsertFieldId = 0;

                        if (bbool)
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewCheckBoxCell());
                        }
                        else
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewTextBoxCell());
                        }
                        MyDge.Rows[mInsertFieldId].Cells[0].Value = fieldName + "-" + mfield.Name;
                        MyDge.Rows[mInsertFieldId].Cells[1].Value = GetEnumDescrip(mfield);

                        if (bbool)
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2] = new DataGridViewCheckBoxCell() { Value = mobj[mfield.Name].ToString().Contains("rue") };

                        }
                        else
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2].Value = mobj[mfield.Name].ToString();
                        }
                        ((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[mInsertFieldId].Cells[0]);
                    }

                    foreach (var mfield in mProperties)
                    {
                        bool bbool = mfield.PropertyType.Name.Contains("ool");

                        int mInsertFieldId = 0;

                        if (bbool)
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewCheckBoxCell());
                        }
                        else
                        {
                            mInsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewTextBoxCell());
                        }

                        MyDge.Rows[mInsertFieldId].Cells[0].Value = fieldName + "-" + mfield.Name;
                        MyDge.Rows[mInsertFieldId].Cells[1].Value = GetEnumDescrip(mfield);

                        if (bbool)
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2] = new DataGridViewCheckBoxCell() { Value = mobj[mfield.Name].ToString().Contains("rue") };

                        }
                        else
                        {
                            MyDge.Rows[mInsertFieldId].Cells[2].Value = mobj[mfield.Name].ToString();
                        }
                    ((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[mInsertFieldId].Cells[0]);
                    }
                }

                MyDge.Update();
            }
            catch (Exception ee)
            {
                if(mShowErrMsg!=null)
                mShowErrMsg("showDataToGride显示空跑位置数据异常:" + ee.ToString());
            }
        }
        public bool  GetDataFromGride( bool bSave=true )
        {
            try
            {
                if (NewSysInf.NewParamse == null)
                    NewSysInf.NewParamse = new NewSysInf.NewParasAll();
                var DataOaobj = NewSysInf.NewParamse;
                var obj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(NewSysInf.NewParamse));
                Type t = typeof(NewSysInf.NewParasAll);
                FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                var Properties = t.GetProperties();
                foreach (FieldInfo field in fields)
                {
                    var fieldTypeName = field.FieldType.Name;
                    var fieldName = field.Name;

                    string StrDataobj = obj[field.Name].ToString();
                    Type temp = field.FieldType;
                    var mtype = field.FieldType;
                    object curobj = new object();
                    curobj = JsonConvert.DeserializeObject(StrDataobj, mtype);

                    if(curobj == null)
                    {
                        continue;
                    }

                    var mobj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(curobj));
                    FieldInfo[] mfields = temp.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    var mProperties = t.GetProperties();
                    foreach (FieldInfo mfield in mfields)
                    {

                        for (int i = 0; i < MyDge.Rows.Count; i++)
                        {
                            
                            var row = MyDge.Rows[i];
                            if (row.Cells[0].Value.ToString() == fieldName + "-" + mfield.Name)
                            {     .                 
                                     bool bbool =  mfield.FieldType == typeof(bool).Name;
                                     //注意bool类型要
                                        if (bbool )
									   {
									       mobj[mfield.Name] =(bool)  row.Cells[2]..Value;
									   } else
									   {
									   mobj[mfield.Name] = row.Cells[2].Value.ToString();
									   }                   
                            }
                        }
                    }

                   

                    foreach (var mfield in mProperties)
                    {

                        for (int i = 0; i < MyDge.Rows.Count; i++)
                        {

                            var row = MyDge.Rows[i];
                            if (row.Cells[0].Value.ToString() == fieldName + "-" + mfield.Name)
                            {
                              bool bbool =  mfield.FieldType == typeof(bool).Name;
                                     //注意bool类型要
                                        if (bbool )
									   {
									       mobj[mfield.Name] =(bool)  row.Cells[2]..Value;
									   } else
									   {
									   mobj[mfield.Name] = row.Cells[2].Value.ToString();
									   }                   

                            }
                        }
                    }

                    obj[field.Name] = JsonConvert.SerializeObject(mobj);

                }

                foreach (var field in Properties)
                {
                    var fieldTypeName = field.PropertyType.Name;
                    var fieldName = field.Name;

                    string StrDataobj = obj[field.Name].ToString();
                    Type temp = field.PropertyType;
                    var mtype = field.PropertyType;
                    object curobj = new object();
                    curobj = JsonConvert.DeserializeObject(StrDataobj, mtype);

                    if (curobj == null)
                    {
                        continue;
                    }

                    var mobj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(curobj));
                    FieldInfo[] mfields = temp.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    var mProperties = t.GetProperties();
                    foreach (FieldInfo mfield in mfields)
                    {

                        for (int i = 0; i < MyDge.Rows.Count; i++)
                        {

                            var row = MyDge.Rows[i];
                            if (row.Cells[0].Value.ToString() == fieldName + "-" + mfield.Name)
                            {
                                bool bbool =  mfield.FieldType == typeof(bool).Name;
                                     //注意bool类型要
                                        if (bbool )
									   {
									       mobj[mfield.Name] =(bool)  row.Cells[2]..Value;
									   } else
									   {
									   mobj[mfield.Name] = row.Cells[2].Value.ToString();
									   }                   

                            }
                        }
                    }



                    foreach (var mfield in mProperties)
                    {

                        for (int i = 0; i < MyDge.Rows.Count; i++)
                        {

                            var row = MyDge.Rows[i];
                            if (row.Cells[0].Value.ToString() == fieldName + "-" + mfield.Name)
                            {
                                bool bbool =  mfield.FieldType == typeof(bool).Name;
                                     //注意bool类型要
                                        if (bbool )
									   {
									       mobj[mfield.Name] =(bool)  row.Cells[2]..Value;
									   } else
									   {
									   mobj[mfield.Name] = row.Cells[2].Value.ToString();
									   }                   

                            }
                        }
                    }

                    obj[field.Name] = JsonConvert.SerializeObject(mobj);
                }

                string ss = obj.ToString();
                ss = ss.Replace("\\r\\n", "");
                ss = ss.Replace("\r\n", "");
                ss = ss.Replace("\\", "");
                ss = ss.Replace(": \"{", ":{");
                ss = ss.Replace("}\"", "}");

                NewSysInf.NewParamse = JsonConvert.DeserializeObject<NewSysInf.NewParasAll>(ss);
                if (bSave)
                    return NewSysInf.SaveSysInf();
                return true;
            }
            catch (Exception ee)
            {
                if (mShowErrMsg != null)
                    mShowErrMsg("getDataFromGride加载空跑位置数据异常:" + ee.ToString());
                return false;
            }

        }

        private void MyDge_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var mcell = MyDge.SelectedCells[0];
            if (mcell.ColumnIndex == 0)
            {
                var newCell = (DataGridViewGroupCell)mcell;
                if (newCell.ChildCells.Length > 0)
                {
                    newCell.UpdataShowChild();
                }
            }

        }


        private void PasteData()
        {
            string clipboardText = Clipboard.GetText(); //获取剪贴板中的内容
            if (clipboardText.Substring(clipboardText.Length - 1, 1) != "\n")
            {
                clipboardText += "\n";
            }
            if (string.IsNullOrEmpty(clipboardText))
            {
                return;
            }
            int colnum = 0;
            int rownum = 0;
            for (int i = 0; i < clipboardText.Length; i++)
            {
                if (clipboardText.Substring(i, 1) == "\t")
                {
                    colnum++;
                }
                if (clipboardText.Substring(i, 1) == "\n")
                {
                    rownum++;
                }
            }
            colnum = colnum / rownum + 1;
            int selectedRowIndex, selectedColIndex;
            selectedRowIndex = this.MyDge.CurrentRow.Index;
            selectedColIndex = this.MyDge.CurrentCell.ColumnIndex;
            if (selectedRowIndex + rownum > MyDge.RowCount || selectedColIndex + colnum > MyDge.ColumnCount)
            {
                MessageBox.Show("粘贴区域大小不一致");
                return;
            }
            String[][] temp = new String[rownum][];
            for (int i = 0; i < rownum; i++)
            {
                temp[i] = new String[colnum];
            }
            int m = 0, n = 0, len = 0;
            while (len != clipboardText.Length)
            {
                String str = clipboardText.Substring(len, 1);
                if (str == "\t")
                {
                    n++;
                }
                else if (str == "\n")
                {
                    m++;
                    n = 0;
                }
                else
                {
                    temp[m][n] += str;
                }
                len++;
            }
            for (int i = selectedRowIndex; i < selectedRowIndex + rownum; i++)
            {
                for (int j = selectedColIndex; j < selectedColIndex + colnum; j++)
                {
                    this.MyDge.Rows[i].Cells[j].Value = temp[i - selectedRowIndex][j - selectedColIndex];
                }
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //在检测到按Ctrl+V键后,系统无法复制多单元格数据,重写ProcessCmdKey方法,屏蔽系统粘贴事件,使用自定义粘贴事件,在事件中对剪贴板的HTML格式进行处理,获取表数据,更新DataGrid控件内容
            if (keyData == (Keys.V | Keys.Control))  // &&
            {
                IDataObject idataObject = Clipboard.GetDataObject();
                string[] s = idataObject.GetFormats();
                string data;
                if (!s.Any(f => f == "OEMText"))
                {
                    if (!s.Any(f => f == "HTML Format"))
                    {
                    }
                    else
                    {
                        //data = idataObject.GetData("HTML Format").ToString();//多个单元格
                        //copyClipboardHtmltoGrid(data);
                        PasteData();
                        //msg = Message.;
                        msg = new Message();
                        return base.ProcessCmdKey(ref msg, Keys.Control);
                    }
                }
                else
                    data = idataObject.GetData("OEMText").ToString();//单个单元格,使用系统功能,无需处理
            }
            MyDge.Update();
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }

    public class NewSysInf
    {

        public class NoneRuntrayUnit
        {
            [Description("大Xx工作位置")]
            public double XxUp;
            [Description("大Xx下料盘位置")]
            public double XxDown;
            [Description("小x上料工作位置")]
            public double x;
            [Description("料盘z上升位置")]
            public double z;
        }
     
        // 类型设置
        public class UserSet
        {
            [Description("红灯亮蜂鸣响")]
            public bool RedLightSund;

        }
        public class NoneRunAll
        {
            [Description("常见设置开启关闭")]
            public UserSet UserNormalSet = new UserSet();

        }

        [Description("空跑位置参数")]
        public static NoneRunAll NoneRunPosInfo = new NoneRunAll();


        public static bool LoadSysInfCfg( out string errMsg)
        {
            errMsg = "";
            try
            {
                //产品参数
                string filename = string.Format("{0}\\product\\NewSysInf.ini", Path.GetFullPath(".."));

                if (!File.Exists(filename))
                {
                    errMsg = string.Format("{0}加载NewSysInf配置文件不存在!", "LoadSysInfCfg");
                    return false;
                }

                IniFile inf = new IniFile(filename);

                var AllPosStr = inf.ReadString("OTHER_SET", "NoneRunPosInfo", "");
                if (AllPosStr.Length > 10)
                {
                    NewSysInf.NoneRunPosInfo = JsonConvert.DeserializeObject<NewSysInf.NoneRunAll>(AllPosStr);
                    return true;
                }

                return false;
            }
            catch (Exception ee)
            {
                return false;
            }
        }

        public static bool SaveSysInf( out string errmsg)
        {
            errmsg = "";
            try
            {
                EM_RES res = EM_RES.OK;
                //产品参数
                string filename = string.Format("{0}\\product\\NewSysInf.ini", Path.GetFullPath(".."));
            
                if (!File.Exists(filename))
                {
                     new FileStream(filename, FileMode.Create);
                }
               
                string[] backup = File.ReadAllLines(filename);
                bool ischange = false;
                //if (!File.Exists(filename))
                //{
                //    VAR.msg.AddMsg(Msg.EM_MSGTYPE.ERR, string.Format("{0}保存异常对应产品名{1}配置文件不存在!", "SavePtCfg", productname));
                //    return EM_RES.PARA_ERR;
                //}
                IniFile inf = new IniFile(filename);
                //门禁

                var EqpPos = JsonConvert.SerializeObject(NewSysInf.NoneRunPosInfo);
                inf.WriteString("OTHER_SET", "NoneRunPosInfo", EqpPos, ref ischange, true, filename);
                if (ischange)
                {
                    //创建backup
                    string backup_filename = string.Format("{0}\\product\\backup", Path.GetFullPath(".."));
                    res = SYS_PUD.CopyFile2(backup_filename);
                    if (res != EM_RES.OK) return false;
                    res = SYS_PUD.FileWriteLine("NewSysInf.ini", backup, backup_filename);
                    if (res != EM_RES.OK) return false;
                }

                return true;
            }catch(Exception ee)
            {
                return false;
            }
        }
    }

}

## 控件设计类

```csharp
namespace UI
{
    partial class DataGrideSysInfo
    {
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.MyDge = new UI.DefineDataGridView();
            this.Column1 = new UI.DataGridViewGroupColumn();
            this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column4 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            this.Column5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.MyDge)).BeginInit();
            this.SuspendLayout();
            // 
            // MyDge
            // 
            this.MyDge.AllowUserToAddRows = false;
            this.MyDge.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.MyDge.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2,
            this.Column3,
            this.Column4,
            this.Column5});
            this.MyDge.Dock = System.Windows.Forms.DockStyle.Fill;
            this.MyDge.Location = new System.Drawing.Point(0, 0);
            this.MyDge.Name = "MyDge";
            this.MyDge.RowHeadersWidth = 30;
            this.MyDge.RowTemplate.Height = 23;
            this.MyDge.ShowRowHeaderNumbers = true;
            this.MyDge.Size = new System.Drawing.Size(868, 494);
            this.MyDge.TabIndex = 1;
            this.MyDge.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.MyDge_CellMouseDoubleClick);
            // 
            // Column1
            // 
            this.Column1.FillWeight = 200F;
            this.Column1.HeaderText = "名称";
            this.Column1.Name = "Column1";
            this.Column1.ReadOnly = true;
            this.Column1.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.Column1.Width = 250;
            // 
            // Column2
            // 
            this.Column2.HeaderText = "说明";
            this.Column2.Name = "Column2";
            this.Column2.Width = 250;
            // 
            // Column3
            // 
            this.Column3.HeaderText = "通用值";
            this.Column3.Name = "Column3";
            this.Column3.Width = 120;
            // 
            // Column4
            // 
            this.Column4.HeaderText = "布尔值";
            this.Column4.Name = "Column4";
            this.Column4.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.Column4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            this.Column4.Width = 80;
            // 
            // Column5
            // 
            this.Column5.HeaderText = "备注";
            this.Column5.Name = "Column5";
            // 
            // DataGrideSysInfo
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.MyDge);
            this.Name = "DataGrideSysInfo";
            this.Size = new System.Drawing.Size(868, 494);
            ((System.ComponentModel.ISupportInitialize)(this.MyDge)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private DefineDataGridView MyDge;
        private DataGridViewGroupColumn Column1;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
        private System.Windows.Forms.DataGridViewCheckBoxColumn Column4;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column5;
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Reflection;
using System.Runtime.Serialization.Formatters;

namespace json
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string mtext = JsonConvert.SerializeObject(ObjDataA);
            richTextBox1.Text = mtext;


        }
        public static DataA ObjDataA = new DataA()
        {
            X = 1.1,
            Y = 2,
            S = "测试",
            mm = new DataB { X = 123 }
        
        };
        public static string GetEnumDescription<T>(T obj)
        {
            var type = obj.GetType();
            FieldInfo field = type.GetField(Enum.GetName(type, obj));
            DescriptionAttribute descAttr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descAttr == null)
                return string.Empty;
            return descAttr.Description;
        }

        public static string GetEnumDescrip(FieldInfo field)
        {
        
            DescriptionAttribute descAttr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descAttr == null)
                return string.Empty;
            return descAttr.Description;
        }
        public class DataA
        {
            [Description("方向X位置")]
            public double X;
            [Description("方向Y位置")]
            public int Y;
            [Description("说明信息")]
            public string S;
            [Description("特殊字符")]
            public DataB mm ;
        }
        
        public class DataB
        {
            public double X;
            public int Y;
        }

   
        private void button1_Click(object sender, EventArgs e)
        {
            var obj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(ObjDataA));
            richTextBox1.Text = obj.ToString();
            //string mtext = JsonConvert.SerializeObject(ObjDataA);
            //richTextBox1.Text = mtext;
        }

        private void button2_Click(object sender, EventArgs e)
        {

           
            var obj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(ObjDataA));
            Type t = typeof(DataA);
            FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            MyDge.Rows.Clear();
            int InsertClassId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
            MyDge.Rows[InsertClassId].Cells[0].Value = t.Name;
            MyDge.Rows[InsertClassId].Cells[1].Value = "";
            MyDge.Rows[InsertClassId].Cells[2].Value = "";
            foreach (FieldInfo field in fields)
            {
                int InsertFieldId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
                MyDge.Rows[InsertFieldId].Cells[0].Value = t.Name;
                MyDge.Rows[InsertFieldId].Cells[1].Value = field.Name+ GetEnumDescrip(field);
                MyDge.Rows[InsertFieldId].Cells[2].Value = obj[field.Name].ToString();
                ((DataGridViewGroupCell)MyDge.Rows[InsertClassId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[InsertFieldId].Cells[0]);
            }
            MyDge.Update();
        }
//从表格获取数据数据层数低的
        private void button3_Click(object sender, EventArgs e)
        {
            string mtext = richTextBox1.Text;

            var obj = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(ObjDataA));
            Type t = typeof(DataA);
            FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            for (int i = 0; i < MyDge.Rows.Count; i++)
            {
                var row = MyDge.Rows[i];
                foreach (FieldInfo field in fields)
                {
                    if (row.Cells[0].Value.ToString() == t.Name)
                    {
                        if (row.Cells[1].Value.ToString() == field.Name + GetEnumDescrip(field))
                        {

                                obj[field.Name] = row.Cells[2].Value.ToString();
                        }
                    }
                }
            }
            //为了处理叠加类DataB字段mm的异常
            string ss = obj.ToString();
            ss = ss.Replace("\\r\\n", "");
            ss = ss.Replace("\r\n", "");
            ss = ss.Replace("\\", "");
            ss = ss.Replace(": \"{", ":{");
            ss = ss.Replace("}\"", "}");

            ObjDataA = JsonConvert.DeserializeObject<DataA>(ss);
        }








    }


}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值