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; namespace daq_testing { public partial class UserControlPslineConfig : UserControl { private BindingList gridData; private FileHandler fileHandler; public event EventHandler UpdateBtnClick; public void OnUpdateBtnClick(EventArgs e) { LoadDgv(); UpdateBtnClick?.Invoke(this, EventArgs.Empty); } public List Data { get; set; } public UserControlPslineConfig() { InitializeComponent(); dgvPslinesConfig.CellContentClick += dgvPslinesConfig_CellContentClick; dgvPslinesConfig.CurrentCellDirtyStateChanged += dgvPslinesConfig_CurrentCellDirtyStateChanged; } public void button1_Click(object sender, EventArgs e) { LoadDgv(); OnUpdateBtnClick(EventArgs.Empty); } public void LoadDgv_old() { BindingSource bs = new BindingSource(); bs.DataSource = Data; dgvPslinesConfig.DataSource = bs; dgvPslinesConfig.Update(); } public void LoadDgv() { string filePath = @"c:\configs\data.json"; fileHandler = new FileHandler(filePath); // Load data gridData = fileHandler.LoadData(); // Bind data to DataGridView dgvPslinesConfig.DataSource = gridData; // Set column properties dgvPslinesConfig.Columns["Psline"].HeaderText = "Psline"; dgvPslinesConfig.Columns["Description"].HeaderText = "Description"; dgvPslinesConfig.Columns["Setpoint"].HeaderText = "Setpoint"; dgvPslinesConfig.Columns["Tolerance"].HeaderText = "Tolerance"; dgvPslinesConfig.Columns["Enabled"].HeaderText = "Enabled"; } private void btnSave_Click(object sender, EventArgs e) { fileHandler.SaveData(gridData); OnUpdateBtnClick(EventArgs.Empty); } private void dgvPslinesConfig_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == dgvPslinesConfig.Columns["Enabled"].Index) { // Check if the Enabled cell was set to true if (Convert.ToBoolean(dgvPslinesConfig.Rows[e.RowIndex].Cells["Enabled"].Value) == true) { // Check for duplicates var pslineValue = dgvPslinesConfig.Rows[e.RowIndex].Cells["Psline"].Value; var hasDuplicate = dgvPslinesConfig.Rows .Cast() .Where(row => Convert.ToBoolean(row.Cells["Enabled"].Value) == true && row.Cells["Psline"].Value.Equals(pslineValue) && row.Index != e.RowIndex) // Exclude the current row .Any(); if (hasDuplicate) { // Revert the change and notify the user dgvPslinesConfig.Rows[e.RowIndex].Cells["Enabled"].Value = false; // Set back to false MessageBox.Show("Cannot enable this row because a duplicate Psline entry exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } private void dgvPslinesConfig_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dgvPslinesConfig.IsCurrentCellDirty) { dgvPslinesConfig.CommitEdit(DataGridViewDataErrorContexts.Commit); } } } }