【问题标题】:How to validate Null or Empty cell in DataGrid如何验证 DataGrid 中的 Null 或 Empty 单元格
【发布时间】:2014-07-10 20:54:00
【问题描述】:

我正在尝试验证 DataGrid 中的单元格。这是我的第一种验证方法。由于我是新手,所以我在验证方面遇到了一些问题。

我创建了一个名为 StringIsNullOrEmptyValidationRule.cs 的类。此类检查字符串是否为空或“”

这里是 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;
    }
}

现在我在 MainWindow.xaml 中有一个数据网格,它绑定到名为 People 的 ObservableCollection。这是我的数据网格:

<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>

问题:

我在 StringIsNullOrEmptyValidationRule 的 Validate Method 的第一行设置了一个断点。 当我没有在姓氏列下的单元格中输入任何数据,并尝试离开单元格时,它没有命中断点,这意味着验证甚至没有检查。

如果我在 lastName 列下的单元格中输入一些数据,然后尝试离开该单元格,它会尝试验证该单元格。所以它到达了断点。

那么,我的问题是如何验证 NullOrEmpty Cell?

【问题讨论】:

  • 如果有人认为我使用了过时的验证方法,那么请提出新的方法。

标签: c# wpf validation datagrid


【解决方案1】:

ValidationRule 仅在属性值更改的情况下有效。但是,当您从空单元格开始时,值并没有改变。因此,在这种情况下不会触发验证规则。

在 Person 类上实现 IDataErrorInfo 并在那里进行验证,如下所示:

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;
        }
    }
}

在您的 XAML 中,您需要将 ValidatesOnDataError 属性设置为 true 以进行姓氏绑定:

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

【讨论】:

  • Person 类由实体框架自动生成。我还应该使用您建议的方法吗?
  • 是的,你可以将它与 EF 生成的类一起使用。
  • 链接here 可能您也感兴趣。
  • 感谢您的回答和文章。我也会读那篇文章。
【解决方案2】:

这是在此处检索到的: http://msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.90).aspx

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
    string headerText = dataGridView1.Columns[e.ColumnIndex].HeaderText;

    // Abort validation if cell is not in the CompanyName column. 
    if (!headerText.Equals("CompanyName")) return;

    // Confirm that the cell is not empty. 
        if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            dataGridView1.Rows[e.RowIndex].ErrorText =
            "Company Name must not be empty";
             e.Cancel = true; 
}

基本上,您可以使用条件语句来验证数据。

这显然是验证单元格中是否存在某些东西的最标准方法...

【讨论】:

  • 感谢您的努力。抱歉,我忘了在问题中提到我很想得到一个对 MVVM 友好的答案。
  • 您提供的解决方案也是针对Winforms的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2014-07-26
  • 2011-01-27
  • 2021-12-29
  • 2020-02-01
相关资源
最近更新 更多