Reputation: 1145
I am a beginner with c # and Visual Studio. Nowadays, I'm doing a program that has the following GUI. In this program the user inserts a value (in the value cell), according to that its correction value is calculated, through a mathematical formula. At this moment, the event that I am using to trigger the calculation of the correction value is dataGridView1_CellEnter (see code below). It works perfectly when I click the cell where the value was modified. However, I would like to do this process automatically, without clicking any cell. Is there any event recognizes the value of a cell is automatically changed or any ideas how to implement it? I would appreciate your help. :)
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e){
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value != null){
j = e.RowIndex;
actualValue = float.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
IsValidMesswert();
}
else {
if (dataGridView1.CurrentCell.ColumnIndex == 1){
MessageBox.Show("Introduce a value", "value");
}
}
}
Upvotes: 0
Views: 306
Reputation: 9469
Have you considered using a DataTable
? Assuming that the values in the “Value” column are generated from some of the other cells in the same row, then, this appears to be a computed value and not part of the data itself. You can add the column to the grid and manually manage it as you describe… or you could add the column to the DataTable
and then set that columns Expression
to the formula you want using the other cells from the same row... then managing these "changing” values will be automatic.
Below is a simple example of what I described above.
There is a Form
with an empty DataGridView
. A DataTable
is created and some data is added to the table. This table is used as a DataSource
for the DataGridView
.
When loaded, the user may change values in the “Value1” or “Value2” columns. After doing so, the “Result” column cell will automatically update to reflect the change. The current formula simply multiplies the two values. I hope this may help.
DataTable gridTable;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
gridTable = getTable();
FillGrid(gridTable);
dataGridView1.DataSource = gridTable;
}
private DataTable getTable() {
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Value1", typeof(int));
dt.Columns.Add("Value2", typeof(int));
dt.Columns.Add(GetFormulaColumn());
return dt;
}
private DataColumn GetFormulaColumn() {
DataColumn dc = new DataColumn("Result", typeof(int));
dc.Expression = "Value1 * Value2";
return dc;
}
private void FillGrid(DataTable dt) {
for (int i = 0; i < 10; i++) {
dt.Rows.Add("ID" + i, i, i + 3);
}
}
Upvotes: 1