How to get datagridview cell state in c #

I have a datagridview, dgv1 with 10 columns in C # form, it is limited to a DB table. The second column is a field with a list of values, closing / opening / for review. The user can change the vauli in any cells. After making changes, the user can click the "Save" button to save the changes to the DB table. But before saving the change, it is necessary to perform one more task: if any value of the second column has changed, it is necessary to call the database stored procedure.

My problem is that I don’t know how to find out if the value of the cell has changed or not, and I also need to know the previous values, the previous and current values ​​should go to the stored procedure.

foreach (DataRow rows in dtList.Rows) { if(rows.RowState.ToString() == "Modified") { if(rows.cell(1) is changed) { call stored procedure here... } } i++; } 
+4
source share
2 answers

One simple (but probably not the best way!) Would use List to store ComboBox values. When loading the form, we can write:

 const int yourCell = 1; List<string> colComboValues = new List<string>(); foreach (DataGridViewRow dgvRow in this.dataGridView.Rows) { DataGridViewComboBoxCell CB = dgvRow.Cells[yourCell] as DataGridViewComboBoxCell; colComboValues.Add(CB.Value.ToString()); } 

and then when saving, we can check which of these ComboBox have changed using:

 // On Save. int nIdx = 0; foreach (DataGridViewRow dgvRow in this.dataGridView.Rows) { DataGridViewComboBoxCell CB = dgvRow.Cells[yourCell] as DataGridViewComboBoxCell; if (String.Compare(CB.Value.ToString(), colComboValues[nIdx++], false) != 0) { // Value has changed! } else { // Value has not. } } 

Hope this helps.

0
source

If you subscribe to CellBeginEdit and CellEndEdit events and add the results to the dictionary, if changes have occurred, the end result is that you just iterate over the dictionary that will contain the cell as its key, and (in my case, the object in your list box values ) previous value before editing.

  Dictionary<DataGridViewCell, object> cvDict = new Dictionary<DataGridViewCell, object>(); private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { DataGridViewCell dgcv = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex]; if (!cvDict.ContainsKey(dgcv)) { cvDict.Add(dgcv, dgcv.Value); } } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { DataGridViewCell dgcv = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cvDict.ContainsKey(dgcv)) { if (cvDict[dgcv].Equals(dgcv.Value)) { cvDict.Remove(dgcv); } } } 
0
source

Source: https://habr.com/ru/post/1395801/


All Articles