Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Detect row validation errors in C# code

Tags:

c#

wpf

.net-4.0

I want to achieve a pretty simple task, but none of the solutions here on SO or otherwise found have helped me so far:

I have a WPF DataGrid, which is bound to a typed data set. When I click the OK button in my window, I want to detect whether there are currently any row validation errors. I want to show a message box and tell the user to resolve these errors.

How can I achieve this?

EDIT
To make my question a bit more precise:

The typed dataset I'm binding to is a simple data set that contains a table. The tables is filled from a call to a WCF service and there are 5 text columns in the table. Some of these columns have length constraints (for example, one column may only take 5 characters).

The ItemsSource of my GridView is set in code as follows:

dgvData.ItemsSource = m_dataModel.TableName;

If I enter some text into the columns, all is well. Entering more than 5 characters into said column, the red row error marker is displayed next to the row. I am not doing any custom validation (yet).

I can see the red exclamation mark, but I'm not able to determine in code whether it is visible or not. I've tried to:

  • Use the data set's HasErrors property (returns false)
  • Validation.GetHasErrors(dgvData) returns false as well
  • the soluction H.B.'s mentioned in his comment, but it didn't work

I'm at a loss here - there must be a simple way of doing this?

like image 895
Thorsten Dittmar Avatar asked Dec 28 '22 15:12

Thorsten Dittmar


1 Answers

OK, I've worked it out. The following does what I want:

public static DataGridRow GetRow(DataGrid grid, int index)
{
    DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        grid.UpdateLayout();
        grid.ScrollIntoView(grid.Items[index]);
        row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

In the code for my "OK" button I do:

for (int i = 0; i < dgvData.Items.Count; i++)
{
    DataGridRow row = GetRow(dgvData, i);
    if (row != null && Validation.GetHasError(row))
    {
        hasDataGridErrors = true;
        break;
    }
}
like image 104
Thorsten Dittmar Avatar answered Jan 08 '23 18:01

Thorsten Dittmar