Changing datagridview cell value in edit mode

I have a cell in a datagridview in which I display the time in a custom format. I need it when it enters edit mode (for example, by double-clicking), I need to change the string value to an integer representing the time in minutes.

When I try to change the value of a cell in the "CellEnter" event, it does not seem to respond. Actually, it doesn't seem to change the value of the cell in any way.

Please ignore the details of converting time to string and vice versa, my question is how can I successfully change the contents of a cell when the user double-clicks on it.

Edit (code + solution): I used a different column to store the actual value (without formatting). When formatting a cell in this column, I pass the value to a custom format function to populate my column.

private void gridview_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { if (e.ColumnIndex == 3 && e.Value != null && e.Value.ToString() != "") { //fill the unbound textbox column (5) from raw value column (3) string newValue = TimeAttendanceHelper.FormatHourlyDuration(e.Value); gridview.Rows[e.RowIndex].Cells[5].Value = newValue; } } 

And then thanks to TaW, on CellBeginEdit, I show the original value for editing it:

 private void gridview_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex == 5) { //on editing, use the value from raw data column (3) gridview.Rows[e.RowIndex].Cells[5].Value = gridview.Rows[e.RowIndex].Cells[3].Value; } } 

And finally, when CellEndEdit, I reformat the new value:

 private void gridview_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 4) { //update value both in columns 3 & 5 string newValue = tIME_SHIFTDataGridView.Rows[e.RowIndex].Cells[4].Value.ToString(); gridview.Rows[e.RowIndex].Cells[3].Value = newValue; gridview.Rows[e.RowIndex].Cells[4].Value = TimeAttendanceHelper.FormatHourlyDuration(newValue); } } 
+4
source share
1 answer

When the cell is in edit mode, you need to change the text in the edit control, usually a text box. You can get (and hold) a handle to it in the EditingControlShowing event:

 TextBox editBox = null; private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is TextBox) editBox = e.Control as TextBox; } 

But using the CellEnter event CellEnter not a good idea, as it will be called when scrolling or clicking around.

To catch the start of editing, you use the BeginEdit event:

 int yourEditColumn = 5; private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex == yourEditColumn ) { string yourValue = "12345"; dataGridView1.Rows[e.RowIndex].Cells[yourEditColumn ].Value = yourValue; if (editBox != null) editBox.Text = yourValue; } } 
+3
source

All Articles