using System; using System.Data; using System.Data.SqlTypes; using System.Reflection; using System.Windows.Forms; using System.Xml; namespace WinFormDataGridViewDemo { public partial class Form1 : Form { private static Boolean SaveFlag = true; private int diffcount = 0; //初始化 public Form1() { InitializeComponent(); // 初始化 DataGridView dataGridView1.ColumnCount = 4; dataGridView1.Columns[0].Name = "LayoutKey"; dataGridView1.Columns[1].Name = "LayoutValue"; dataGridView1.Columns[2].Name = "SecsKey"; dataGridView1.Columns[3].Name = "SecsValue"; //dataGridView1.Columns[3].Name = "SecsValue"; dataGridView1.Columns[0].ReadOnly = true; dataGridView1.Columns[1].ReadOnly = true; dataGridView1.Columns[2].ReadOnly = true; dataGridView1.Columns[3].ReadOnly = false; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView1.AllowUserToAddRows = false; dataGridView1.AllowUserToAddRows = true; LoadDataGrid(); dataGridView1.Dock = DockStyle.Fill; tableLayoutPanel1.Dock = DockStyle.Fill; dataGridView1.RowPostPaint += dataGridView1_RowPostPaint; dataGridView1.CellFormatting += dataGridView1_CellFormatting; dataGridView1.AllowUserToAddRows = false; //dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.LightGray; int w = 0; foreach (DataGridViewColumn item in dataGridView1.Columns) { w += item.Width; } dataGridView1.Width = w; int borderWidth = this.Width - this.ClientSize.Width; this.Width = dataGridView1.Width + borderWidth + 200; } //加载 private void LoadDataGrid() { SaveFlag = true; var alramLayout = @"D:\iWISEETEC\ABN12\\AlarmLayout_Eng.xml"; var alramSecsXml = @"D:\iWISEETEC\WSecsAgent\\SecsPar\\config\\yui.xml"; if (!string.Empty.Equals(LayoutPath.Text)) { alramLayout = LayoutPath.Text; } if (!string.Empty.Equals(AlarmPath.Text)) { alramSecsXml = AlarmPath.Text; } var layoutResult = LoadAlarmLayoutXML(alramLayout); var secsResult = LoadAlarmSecsXML(alramSecsXml, out XmlDocument doc); dataGridView1.Rows.Clear(); var mergedList = layoutResult.Select(kv => new { LayoutKey = kv.Key, LayoutValue = kv.Value, SecsKey = kv.Key, SecsValue = secsResult.ContainsKey(kv.Key) ? secsResult[kv.Key] : "" }).ToList(); foreach (var item in mergedList) { dataGridView1.Rows.Add(item.LayoutKey, item.LayoutValue, item.SecsKey, item.SecsValue); } diffcount = 0; UpdateDiffCount(); } // 覆盖选中行 private void btnCoverRow_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (row.IsNewRow) continue; var name = row.Cells[1].Value?.ToString(); row.Cells[3].Value = name; } if (dataGridView1.CurrentRow != null) { var rowIndex = dataGridView1.CurrentRow.Index; var code = dataGridView1.Rows[rowIndex].Cells[0].Value?.ToString(); var name = dataGridView1.Rows[rowIndex].Cells[1].Value?.ToString(); dataGridView1.Rows[rowIndex].Cells[3].Value = name; SaveFlag = false; } UpdateDiffCount(); } // 覆盖全部行 private async void btnCoverAll_Click(object sender, EventArgs e) { var rowCount = dataGridView1.Rows.Count; Cursor = Cursors.WaitCursor; //progressBar1.Minimum = 0; panel3.Enabled = false; progressBar1.Value = 0; progressBar1.Maximum = diffcount; progressBar1.Visible = true; var index = 0; await Task.Run(() => { foreach (DataGridViewRow row in dataGridView1.Rows) { var leftValue = row.Cells[1].Value.ToString(); if ("" == leftValue) { continue; } var rightValue = row.Cells[3].Value.ToString(); if (leftValue == rightValue) { continue; } Invoke(() => { index++; return row.Cells[3].Value = leftValue; }); SaveFlag = false; Invoke(() => { progressBar1.Value += 1; }); } diffcount -= index; Invoke(SetDiffCountText); }); progressBar1.Value = 0; panel3.Enabled = true; this.Cursor = Cursors.Default; MessageBox.Show($"已覆盖 {index} 行,请点击【保存】写入XML"); } //行号 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { string rowNumber = (e.RowIndex + 1).ToString(); var headerBounds = new Rectangle( e.RowBounds.Left, e.RowBounds.Top, dataGridView1.RowHeadersWidth, e.RowBounds.Height); TextRenderer.DrawText( e.Graphics, rowNumber, dataGridView1.Font, headerBounds, SystemColors.ControlText, TextFormatFlags.VerticalCenter | TextFormatFlags.Right ); } //差异高亮 private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 3 && e.RowIndex >= 0) { if (dataGridView1.Rows[e.RowIndex].Cells[1].Value?.ToString() != dataGridView1.Rows[e.RowIndex].Cells[3].Value?.ToString()) { //dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 182, 193); dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 200, 200); dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White; } else { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = dataGridView1.DefaultCellStyle.BackColor; dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = dataGridView1.DefaultCellStyle.ForeColor; } } } //统计差异 private void UpdateDiffCount() { if (diffcount != 0) diffcount = 0; var map = new Dictionary(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.IsNewRow) continue; if (!(row.Cells[1].Value.ToString() == row.Cells[3].Value?.ToString())) { diffcount++; } } SetDiffCountText(); } //保存 private void SaveAlarm(object sender, EventArgs e) { if (SaveFlag) { MessageBox.Show("未修改无需保存!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string alramSecsXml = @"D:\iWISEETEC\WSecsAgent\SecsPar\config\yui.xml"; if (!File.Exists(alramSecsXml)) { MessageBox.Show("Secs XML 文件不存在!"); return; } XmlDocument doc = new XmlDocument(); doc.Load(alramSecsXml); XmlNode root = doc.DocumentElement; if (root == null) { MessageBox.Show("XML 根节点不存在!"); return; } XmlNodeList nodes = doc.SelectNodes("//Item"); Dictionary nodeDict = new Dictionary(); if (nodes != null) { foreach (XmlNode node in nodes) { if (node.Attributes?["Code"] != null && int.TryParse(node.Attributes["Code"].Value, out int code)) { nodeDict[code] = node; } } } foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.IsNewRow) continue; if (int.TryParse(row.Cells[2].Value?.ToString(), out int key)) { string newValue = row.Cells[3].Value?.ToString() ?? ""; if (nodeDict.ContainsKey(key)) { // 修改 nodeDict[key].Attributes["Name"].Value = newValue; //Description可能不存在 if (nodeDict[key].Attributes["Description"] != null) { nodeDict[key].Attributes["Description"].Value = newValue; } } else { // 新增 XmlElement newNode = doc.CreateElement("Item"); XmlAttribute codeAttr = doc.CreateAttribute("Code"); XmlAttribute UnitAttr = doc.CreateAttribute("Unit"); XmlAttribute LevelAttr = doc.CreateAttribute("Level"); XmlAttribute nameAttr = doc.CreateAttribute("Name"); XmlAttribute descriptionAttr = doc.CreateAttribute("Description"); XmlAttribute HowToAttr = doc.CreateAttribute("HowTo"); codeAttr.Value = key.ToString(); UnitAttr.Value = "00"; LevelAttr.Value = "W"; nameAttr.Value = newValue; descriptionAttr.Value = newValue; HowToAttr.Value = ""; newNode.Attributes.Append(codeAttr); newNode.Attributes.Append(UnitAttr); newNode.Attributes.Append(LevelAttr); newNode.Attributes.Append(nameAttr); newNode.Attributes.Append(descriptionAttr); newNode.Attributes.Append(HowToAttr); root.AppendChild(newNode); } } } doc.Save(alramSecsXml); MessageBox.Show("保存成功!"); LoadDataGrid(); } //加载xml private Dictionary LoadAlarmLayoutXML(string path) { Dictionary result = new Dictionary(); string xmlContent = File.ReadAllText(path); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlContent); XmlNodeList nodes = doc.SelectNodes("//wAlarmLayout"); foreach (XmlNode node in nodes) { int erCode = int.Parse(node["erCode"].InnerText); string msg = node["Msg"]?.InnerText ?? ""; result[erCode] = msg; } return result; } //加载xml private Dictionary LoadAlarmSecsXML(string path, out XmlDocument doc) { var result = new Dictionary(); doc = new XmlDocument(); doc.Load(path); XmlNodeList nodes = doc.SelectNodes("//Item"); if (nodes == null) return result; foreach (XmlNode node in nodes) { if (node.Attributes == null) continue; string codeStr = node.Attributes["Code"]?.Value; string name = node.Attributes["Name"]?.Value ?? ""; if (int.TryParse(codeStr, out int code)) { result[code] = name; } } return result; } //重载 reloadXml private void reloadXml(object sender, EventArgs e) { LoadDataGrid(); MessageBox.Show($"重新加载成功!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } //加载LayoutXml路径 private void OpenLayoutXml_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { this.LayoutPath.Text = this.openFileDialog1.FileName; LoadDataGrid(); } } //加载SecsAlarm路径 private void SecsAlarm_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { this.AlarmPath.Text = this.openFileDialog1.FileName; LoadDataGrid(); } } //设置lab内容 private void SetDiffCountText() { this.DiffCountLab.Text = $"差异数量:{diffcount}"; } //鼠标点击事件 } }