Check if a cell value in a datagrid binded to an observable collection is empty or duplicated

I searched for a while but I can't figure out how to check if the "Name" column of my datagrid is empty or contains an existing value. If so, the row shouldn't be added to the collection.

This is the class :

public class DataVals : BaseClass, INotifyPropertyChanged 
{
    #region Properties
    [XmlIgnore]
    private string _Name = "";
    [XmlAttribute]
    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            this.PropertyChangedNotify("BindId");
        }
    }

    [XmlAttribute]
    public float Min { get; set; } = 0;

    [XmlAttribute]
    public float Max { get; set; } = 0;

    [XmlAttribute]
    public float ALVal { get; set; } = 0;

    [XmlAttribute]
    public float WLVal { get; set; } = 0;

----
}

The observable collection :

public ObservableCollection<DataVals> ListeDataTable { get; set; } = new ObservableCollection<DataVals>();

The Datagrid is binded to the ListeDataTable :

DgDataTable.ItemsSource = ListeDataTable;

The image bellow shows the issue, I can add rows with empty names:

enter image description here

Thank you for your help.

1 answer

  • answered 2017-01-11 14:18 SnowballTwo

    You can get a collection view and filter it with the following snippet:

    var view = CollectionViewSource.GetDefaultView( ListDataTable );
            view.Filter = item =>
            {
                var dataVal = item as DataVals;
                if( dataVal == null )
                    return false;
    
                return !string.IsNullOrEmpty( dataVal.Name );
            };
    

    The binding uses the default view anyways, so you don't need to do anything else :)