项目场景:
这段代码定义了一个名为 ucDatagridviewHelper 的用户控件(UserControl),该控件包含了一个 DataGridView 控件和一些其他功能。
这段代码的主要部分:
构造函数:在构造函数中,初始化了用户控件的一些属性,设置了控件的样式以减少闪烁,订阅了 DataGridView 的一些事件(例如 MouseDown、DragOver、DragDrop 等),并且设置了双缓冲以优化性能。
MouseDown 事件处理程序:当鼠标按下时,如果是中键(MouseButtons.Middle),则获取鼠标点击的行和列索引,如果列索引为0,则将该行设置为拖动的行(draggingRow),并且开始拖拽操作。
DragOver 事件处理程序:处理拖放过程中的事件,设置拖放操作的效果为移动。
DragDrop 事件处理程序:处理拖放操作完成后的事件,获取拖放的目标行的索引,并将拖动的行插入到目标行的位置。
ProtocolParas 属性:该属性是一个类(Fox_Inverter_Remote_Protocol.ProtocolPara)的实例,用于管理协议参数。通过该属性的 get 和 set 方法,可以获取和设置 DataGridView 的数据源,并根据协议参数初始化 DataGridView。
cmb_op_SelectedIndexChanged 方法:根据不同的操作类型,显示或隐藏 DataGridView 的某些列。
InitialDatatable 方法:根据传入的故障信息列表,初始化 DataGridView 控件。该方法添加了 DataGridView 的列,并根据不同的类型设置列的可见性。然后,根据故障信息列表添加了 DataGridView 的行,并为每一行设置了单元格的值。
dataGridView1_CellMouseDoubleClick 事件处理程序:处理 DataGridView 单元格的双击事件。如果双击的是第5列(Address 列),则自动生成连续地址,并调用委托 UpdateAddress 更新地址。如果双击的是第7列(Value 列),则弹出一个富文本编辑器窗口,编辑单元格的值。
public class ProtocolPara{/// <summary>/// 0 片读片写 1 片读单写 3 单读单写/// </summary>public int OperateMethod { get; set; }public string BlockName { get; set; }public List<string[]> Description { get; set; } = new List<string[]>();public UInt16 Address { get; set; }public UInt16 Length { get; set; }}public partial class ucDatagridviewHelper : UserControl{public ucDatagridviewHelper(){InitializeComponent();SetStyle(ControlStyles.Selectable, true);SetStyle(ControlStyles.AllPaintingInWmPaint, true);//忽略窗口消息,减少闪烁SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//绘制到缓冲区,减少闪烁SetStyle(ControlStyles.UserPaint, true);//控件由其自身而不是操作系统绘制SetStyle(ControlStyles.ResizeRedraw, true);//控件调整其大小时重绘dataGridView1.RowPostPaint += dataGridView1_RowPostPaint_1;dataGridView1.MouseDown += DataGridView1_MouseDown;dataGridView1.DragOver += DataGridView1_DragOver;dataGridView1.DragDrop += DataGridView1_DragDrop;Type dgvType = dataGridView1.GetType();PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);pi.SetValue(dataGridView1, true, null);dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;}public event Action<int> UpdateAddress;void EnableDgv(DataGridView dgv,bool flag){dgv.AllowUserToAddRows = flag;dgv.AllowUserToResizeRows = flag;dgv.AllowUserToDeleteRows = flag;dgv.AllowUserToOrderColumns = flag;dgv.AllowUserToResizeColumns = flag;}private DataGridViewRow draggingRow;private void DataGridView1_MouseDown(object sender, MouseEventArgs e){dataGridView1.AllowDrop = true;if (e.Button == MouseButtons.Middle){int rowIndex = dataGridView1.HitTest(e.X, e.Y).RowIndex;int colIndex = dataGridView1.HitTest(e.X, e.Y).ColumnIndex;if (rowIndex >= 0&&colIndex==0){draggingRow = dataGridView1.Rows[rowIndex];dataGridView1.DoDragDrop(draggingRow, DragDropEffects.Move);}}}private void DataGridView1_DragOver(object sender, DragEventArgs e){e.Effect = DragDropEffects.Move;}private void DataGridView1_DragDrop(object sender, DragEventArgs e){int rowIndex = dataGridView1.HitTest(dataGridView1.PointToClient(new System.Drawing.Point(e.X, e.Y)).X, dataGridView1.PointToClient(new System.Drawing.Point(e.X, e.Y)).Y).RowIndex;if (rowIndex >= 0){dataGridView1.Rows.Remove(draggingRow);dataGridView1.Rows.Insert(rowIndex, draggingRow);}dataGridView1.AllowDrop = false;}Fox_Inverter_Remote_Protocol.ProtocolPara _ProtocolParas;public Fox_Inverter_Remote_Protocol.ProtocolPara ProtocolParas{get{List<string[]> lst = new List<string[]>();for (int i = 0; i < dataGridView1.Rows.Count; i++){string[] des = new string[dataGridView1.Columns.Count];for (int j = 0; j < dataGridView1.Columns.Count; j++){des[j] = dataGridView1.Rows[i].Cells[j].Value.ToString();}lst.Add(des);}if(dataGridView1.Rows.Count>0)_ProtocolParas.Description = lst;return _ProtocolParas;}set{_ProtocolParas = value;if (_ProtocolParas != null && _ProtocolParas.Description != null){this.dataGridView1.Columns.Clear();this.dataGridView1.Rows.Clear();// 0 片读片写 1 片读单写 3 单读单写if (_ProtocolParas.OperateMethod == 0){InitialDatatable(this.dataGridView1, _ProtocolParas.Description, 0);}else if (ProtocolParas.OperateMethod == 1){InitialDatatable(this.dataGridView1, _ProtocolParas.Description, 1);}else if (ProtocolParas.OperateMethod == 2){InitialDatatable(this.dataGridView1, _ProtocolParas.Description, 2);}else if (ProtocolParas.OperateMethod == 3){InitialDatatable(this.dataGridView1, _ProtocolParas.Description, 3);}}}}public void cmb_op_SelectedIndexChanged(int type){if (dataGridView1.Columns.Count > 7){if (type == 0){dataGridView1.Columns[8].Visible = false;dataGridView1.Columns[9].Visible = false;}else if (type == 1){dataGridView1.Columns[8].Visible = true;dataGridView1.Columns[9].Visible = false;}else if (type == 2){dataGridView1.Columns[8].Visible = true;dataGridView1.Columns[9].Visible = true;}}}#region Initial void InitialDatatable(DataGridView dgv, List<string[]> FaultMessage, int type){dgv.Columns.Add(column_addTextBox("Desc"));dgv.Columns.Add(column_addTextBox("RW"));dgv.Columns.Add(column_addTextBox("Type"));dgv.Columns.Add(column_addTextBox("Unit"));dgv.Columns.Add(column_addTextBox("gain"));dgv.Columns.Add(column_addTextBox("Address"));dgv.Columns.Add(column_addTextBox("Registeres"));dgv.Columns.Add(column_addTextBox("Value"));dgv.Columns.Add(column_addbutton("Write"));dgv.Columns.Add(column_addbutton("Read"));int i = 0;dgv.Columns[i++].FillWeight = 20;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 8;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 10;dgv.Columns[i++].FillWeight = 6;dgv.Columns[i++].FillWeight = 6;if (type == 0){dgv.Columns[8].Visible = false;dgv.Columns[9].Visible = false;}else if (type == 1){dgv.Columns[8].Visible = true;dgv.Columns[9].Visible = false;}else if (type == 2){dgv.Columns[8].Visible = true;dgv.Columns[9].Visible = true;}else{//btn_write.Visible = true;//btn_read.Visible = true;//dataGridView1.Columns[8].Visible = true;//dataGridView1.Columns[8].Visible = true;}for (int h = 0; h < dgv.Columns.Count; h++){dgv.Columns[h].SortMode = DataGridViewColumnSortMode.NotSortable;}for (int j = 0; j < FaultMessage.Count; j++){string[] msg = FaultMessage[j];dgv.Rows.Add();int index = 0;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;dgv.Rows[j].Cells[index].Value = msg[index];index++;int tempindex = index >= msg.Length ? (msg.Length - 1) : index;string[] jgStr = msg[tempindex].Split('/');if (jgStr.Length > 1){//DataGridViewComboBoxCell cbCell = new DataGridViewComboBoxCell();//cbCell.DataSource = jgStr;//cbCell.Value = jgStr[0];//cbCell.Style.BackColor = Color.LightBlue;//cbCell.Style.ForeColor = Color.LightBlue;dgv.Rows[j].Cells[index].Value = msg[index];}else{//dgv.Rows[j].Cells[index].Style.BackColor = Color.LightGray;dgv.Rows[j].Cells[index].Value = "0";}dgv.Rows[j].DefaultCellStyle.BackColor = Color.LightGray;dgv.Rows[j].Cells[8].Value = "Write";dgv.Rows[j].Cells[9].Value = "Read";}EnableDgv(dgv, false);//dgv.RowTemplate.Height = 10;//dgv.RowHeadersVisible = false;dgv.RowHeadersWidth = 30;//dgv.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);}private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e){Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.dataGridView1.RowHeadersWidth - 4, e.RowBounds.Height);TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dataGridView1.RowHeadersDefaultCellStyle.Font,rectangle, this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);}int column_key = 0;private DataGridViewTextBoxColumn column_addTextBox(string name){DataGridViewTextBoxColumn txtClum = new DataGridViewTextBoxColumn();txtClum.DataPropertyName = "txt" + column_key++.ToString();txtClum.Name = "txt" + column_key++.ToString();txtClum.HeaderText = name;return txtClum;}private DataGridViewButtonColumn column_addbutton(string name){DataGridViewButtonColumn txtClum = new DataGridViewButtonColumn();txtClum.DataPropertyName = "txt" + column_key++.ToString();txtClum.Name = "txt" + column_key++.ToString();txtClum.HeaderText = name;//txtClum.DisplayIndex = 5;return txtClum;}private DataGridViewCheckBoxColumn column_addCheckBox(string name){DataGridViewCheckBoxColumn txtClum = new DataGridViewCheckBoxColumn();txtClum.DataPropertyName = "txt" + column_key++.ToString();txtClum.Name = "txt" + column_key++.ToString();txtClum.HeaderText = name;return txtClum;}private DataGridViewComboBoxColumn column_addComboBox(string name, string[] strname){DataGridViewComboBoxColumn txtClum = new DataGridViewComboBoxColumn();txtClum.DataPropertyName = "txt" + column_key++.ToString();txtClum.Name = "txt" + column_key++.ToString();txtClum.HeaderText = name;txtClum.Items.AddRange(strname);//txtClum.DisplayIndex = 1;return txtClum;}#endregionprivate void addToolStripMenuItem_Click(object sender, EventArgs e){int i = dataGridView1.SelectedCells[0].RowIndex;DataGridViewRow dr = new DataGridViewRow();dr.CreateCells(this.dataGridView1);for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++){dr.Cells[j].Value = dataGridView1.Rows[i].Cells[j].Value;}this.dataGridView1.Rows.Insert(i, dr);}private void deleteToolStripMenuItem_Click(object sender, EventArgs e){int i = dataGridView1.SelectedCells[0].RowIndex;dataGridView1.Rows.RemoveAt(i);}private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e){dataGridView1.ClearSelection();if (e.ColumnIndex == 5){for (int i = 0; i < dataGridView1.Rows.Count; i++){dataGridView1.Rows[i].Cells[e.ColumnIndex].Value = Convert.ToUInt16(dataGridView1.Rows[0].Cells[e.ColumnIndex].Value) + i;}UpdateAddress?.Invoke(Convert.ToUInt16(dataGridView1.Rows[0].Cells[e.ColumnIndex].Value));}else if (e.ColumnIndex == 7){if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Length > 15){FrmRichBoxEditor childForm = new FrmRichBoxEditor(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());int parentFormX = this.Location.X;int parentFormY = this.Location.Y;int parentFormWidth = this.Width;int parentFormHeight = this.Height;int childFormWidth = childForm.Width;int childFormHeight = childForm.Height;int childFormX = parentFormX + (parentFormWidth - childFormWidth) / 2;int childFormY = parentFormY + (parentFormHeight - childFormHeight) / 2;// 设置子窗体的位置childForm.StartPosition = FormStartPosition.Manual;childForm.Location = new System.Drawing.Point(childFormX, childFormY);childForm.ShowDialog();dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = childForm.ReValue;}}}}