C # Get cell text value if DataError fires

I have a DataGridView and I dynamically populate it from my database using the following code

 DataGridViewTextBoxColumn colID = new DataGridViewTextBoxColumn(); colID.HeaderText = "id"; colID.DataPropertyName = "id"; colID.ReadOnly = true; colID.Visible = false; dtgvLoadEx.Columns.Add(colID); DataGridViewTextBoxColumn colLoadExpiryDate = new DataGridViewTextBoxColumn(); //CalendarColumn colLoadExpiryDate = new CalendarColumn(); colLoadExpiryDate.HeaderText = "LoadExpiryDate(mm/dd/yy)"; colLoadExpiryDate.Width = 158; colLoadExpiryDate.DataPropertyName = "LoadExpiryDate"; colLoadExpiryDate.ReadOnly = false; colLoadExpiryDate.MaxInputLength = 10; dtgvLoadEx.Columns.Add(colLoadExpiryDate); dtgvLoadEx.DataSource = data(); //Return data table from my Database 

As you can see, I have a Date column. When I try to edit a cell of this column and enter an invalid format, a DataError event will occur.

Now I just want to get the error text from

 private void dtgvLoadEx_DataError(object sender, DataGridViewDataErrorEventArgs e) { } 

or any other process to get the error text.

+6
source share
3 answers

Ok guys, I already solved the problem. Here I am going to share it.

  private void dtgvLoadEx_DataError(object sender, DataGridViewDataErrorEventArgs e) { string s = dtgvLoadEx.EditingControl.Text; } 
+3
source

You want to use the event argument as follows

 string errorText; private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e) { // This will return the last text entry that was not erroneous. string cellValue = dataGridView[e.ColumnIndex, e.RowIndex].Value.ToString(); // This will get the text indicating the error condition. errorText = dataGridView[e.ColumnIndex, e.RowIndex].ErrorText; } 

Change After reading your comment below, if the first of the above does not return an erratic hatch value, then this may not be possible. Use ErrorText .

Hope this helps.

+3
source

You can perform a custom check using the CellValidating event:

 private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (!DateTime.TryParse(e.FormattedValue)) { string s = e.FormattedValue; e.Cancel = true; } } 
+1
source

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


All Articles