1
votes

So I have a form with a DataGridView getting its data from a DataTable with the following code (AlternativeMenu is the Form, manager.Values is the DataTable).

public AlternativeMenu(Manager m)
{
   InitializeComponent();
   manager = m;
   dataView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
   dataView.AllowUserToAddRows = false;
   dataView.MultiSelect = false;
   dataView.DataSource = manager.Values;
   valueValidation();
}

The valueValidation method checks for invalid values and changes the cell error text and background color.

public void valueValidation()
{
   foreach (DataGridViewColumn column in dataView.Columns)
   {
      foreach (DataGridViewRow row in dataView.Rows)
      {
         validateCell(row.Index, column.Index);
      }
   }
}

private void validateCell(int row, int column)
{
   if (!manager.validateValue(row, dataView.Columns[column].Name))
   {
      dataView.Rows[row].Cells[column].ErrorText = "placeholder error text";
      dataView.Rows[row].Cells[column].Style.BackColor = Color.Salmon;
   }
   else
   {
      dataView.Rows[row].Cells[column].ErrorText = "";
      dataView.Rows[row].Cells[column].Style.BackColor = Color.White;
   }
}

If I call the valueValidation() method from a button press, all the cells with errors are marked with the different color and error text. However I want this to happen as soon as the form is displayed.

2

2 Answers

1
votes

I don't think the DataGridView control likes doing validations in a constructor. Try moving your method call to the OnLoad method instead:

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  valueValidation();
}
0
votes

Try moving the valueValidation(); to your form's Shown-event.

Add this under the foreach loops:

dataView.Refresh();