tbf/GenesisCordonelInterface/UI/Grid/MeterGridManager.cs

108 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace GenesisCordonelInterface.UI.Grid
{
public class MeterGridManager
{
private readonly DataGridView grid;
public MeterGridManager(DataGridView grid)
{
this.grid = grid;
EnableDoubleBuffering(grid);
}
public void Init(List<MeterGridColumnConfig> columns)
{
grid.SuspendLayout();
grid.AutoGenerateColumns = false;
grid.Columns.Clear();
grid.AllowUserToAddRows = false;
grid.AllowUserToDeleteRows = false;
grid.RowHeadersVisible = true;
foreach (var cfg in columns.OrderBy(c => c.DisplayIndex))
{
DataGridViewColumn col;
if (cfg.Name == "Selected" || cfg.Name == "IsLoggedOn")
col = new DataGridViewCheckBoxColumn();
else
col = new DataGridViewTextBoxColumn();
col.Name = cfg.Name;
col.HeaderText = cfg.HeaderText;
col.Visible = cfg.Visible;
col.Width = cfg.Width;
col.ReadOnly = cfg.ReadOnly;
grid.Columns.Add(col);
}
grid.ResumeLayout();
}
public void Update(List<MeterRowDto> meters)
{
grid.SuspendLayout();
foreach (var meter in meters)
{
var row = FindOrCreateRow(meter.Slot);
SetCell(row, "Slot", meter.Slot);
SetCell(row, "Selected", meter.Selected);
SetCell(row, "PcbId", meter.PcbId);
SetCell(row, "IsConnected", meter.IsConnected);
SetCell(row, "IsLoggedOn", meter.IsLoggedOn);
SetCell(row, "RequestPort", meter.RequestPort);
SetCell(row, "StreamingPort", meter.StreamingPort);
SetCell(row, "FwVersion", meter.FwVersion);
SetCell(row, "InterfaceVersion", meter.InterfaceVersion);
}
grid.ResumeLayout();
}
private DataGridViewRow FindOrCreateRow(int slot)
{
foreach (DataGridViewRow row in grid.Rows)
{
if (row.Cells["Slot"].Value != null &&
Convert.ToInt32(row.Cells["Slot"].Value) == slot)
{
return row;
}
}
int idx = grid.Rows.Add();
var newRow = grid.Rows[idx];
newRow.Cells["Slot"].Value = slot;
return newRow;
}
private void SetCell(DataGridViewRow row, string colName, object value)
{
if (!grid.Columns.Contains(colName))
return;
var cell = row.Cells[colName];
if (!Equals(cell.Value, value))
cell.Value = value;
}
private void EnableDoubleBuffering(DataGridView dgv)
{
typeof(DataGridView)
.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic)
?.SetValue(dgv, true, null);
}
}
}