How to validate Null or Empty cell in DataGrid

c#, datagrid, validation, wpf

Solution

ValidationRule works only in case property value is changed. But, when you go from empty cell, value has not changed. Hence, validation rule won't fired in that case.

Implement IDataErrorInfo on Person class and do your validation over there something like this:

public class Person : IDataErrorInfo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }

    public string Error
    {
        get
        {
            return String.Concat(this[FirstName], " ", this[LastName], " ",
                                 this[City]);
        }
    }

    public string this[string columnName]
    {
        get
        {
            string errorMessage = null;
            switch (columnName)
            {
                case "LastName":
                    if (String.IsNullOrWhiteSpace(LastName))
                    {
                        errorMessage = "LastName is required.";
                    }
                    break;
            }
            return errorMessage;
        }
    }
}

And in your XAML, you need to set `ValidatesOnDataError` property to true for LastName binding:

<DataGridTextColumn Header="Last Name" Binding="{Binding LastName, 
                                           ValidatesOnDataErrors=True}"/>

Problem

I am trying to Validate a cell in DataGrid. This is my first approach to validation. I get some problems with validations as I am new to it. I have created a class called StringIsNullOrEmptyValidationRule.cs. This class checks if string is null or "" Here is the code of StringIsNullOrEmptyValidationRule.cs : ``` class StringIsNullOrEmptyValidationRule : ValidationRule { private string _errorMessage = ""; public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; } } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { ValidationResult result = new ValidationResult(true, null); if (value == null || ((string)value).Trim() == "") { result = new ValidationResult(false, this.ErrorMessage); } return result; } } ``` Now I have a datagrid in MainWindow.xaml which is bound to an ObservableCollection called People. Here is my DataGrid : ``` <DataGrid x:Name="maindg" ItemsSource="{Binding People}" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="CellOrRowHeader"> <DataGrid.Columns> <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" /> <DataGridTextColumn Header="Last Name"> <DataGridTextColumn.Binding> <Binding Path="LastName"> <Binding.ValidationRules> <local:StringIsNullOrEmptyValidationRule ErrorMessage="LastName is required" /> </Binding.ValidationRules> </Binding> </DataGridTextColumn.Binding> </DataGridTextColumn> <DataGridTextColumn Header="City" Binding="{Binding City}" /> </DataGrid.Columns> </DataGrid> ``` Problem : I kept a breakpoint on StringIsNullOrEmptyValidationRule's Validate Method's first line. When I don't enter any data in a cell under LastName Column, and try to move away from the cell, it does not hit breakpoint, that means validation does not even check. If I enter some data to the cell under lastName column and then try to move away from the cell, it tries to validates the cell. So it hits the breakpoint. So, my question is how can I validate NullOrEmpty Cell?

Original source