I have a datagridview
for which I have included couple of validations like cell value not empty and cell value should be in the range of (1,9). I also wanted to make sure a compute button is enabled only after the entire datagridview
is filled with valid values.
I tried to use foreach
and check for the rows and cells inside it if the cell value is not empty, but the button is getting enabled immediately just after checking one cell. Checking for the last cell in each row also doesn't work since user can fill the values in any order and we should try to track the point when all the cells are filled and make the button enabled then. If they aren't filled, we have to make the button disabled immediately. Is there a way I can enable a button only if all the cells are filled and validated accordingly.
Below is my code. I am a bit new to C#, I also wanted to know if I am using the right datagridview
event to achieve this. Instead of looping through each row and cell to find the value, is there an efficient way to find if all the cells are filled or not in one-go?
Cal.Enabled = false;
private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int r = e.RowIndex;
int c = e.ColumnIndex;
foreach (DataGridViewRow row in dataGridView.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if ((cell.Value != null) || cell.Value != DBNull.Value || !(String.IsNullOrEmpty(cell.Value.ToString())))
{
Cal.Enabled = true;
}
}
}
}
You have to check every cell - and if any one cell is invalid, you must disable the button.
As an aside, I think the behaviour is better when you use the CellEndEdit
event, instead of the Validating
event. But both sort of work.
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// We assume every cell is valid
// and then we'll loop until we find one that isn't.
var allValid = true;
foreach (DataGridViewRow row in dataGridView.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
var v = cell.Value;
if(v == null || v == DBNull.Value || string.IsNullOrEmpty(v?.ToString())) {
// We found an invalid cell!
allValid = false;
break;
}
}
// a cell in this row was invalid - no need to check the next row
if(!allValid) break;
}
// Now, if all cells were valid, allValid is still true.
// If any cell was invalid, it's false.
Cal.Enabled = allValid;
}