如何验证数据网格中的Null或空单元格
本文关键字:Null 单元格 网格 数据网 何验证 验证 数据 | 更新日期: 2023-09-27 18:12:36
我正在尝试验证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;
}
}
现在我有一个数据网格在主窗口。xaml绑定到一个名为People的ObservableCollection。这是我的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>
问题:
我在StringIsNullOrEmptyValidationRule的验证方法的第一行上保留了一个断点。当我没有在LastName Column下的单元格中输入任何数据,并尝试离开单元格时,它不会击中断点,这意味着验证甚至不会检查。
如果我在lastName列下的单元格中输入一些数据,然后尝试从该单元格移开,它会尝试验证该单元格。所以它到达了断点
所以,我的问题是我如何验证NullOrEmpty Cell?
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中,您需要为LastName绑定设置 ValidatesOnDataError
属性为true:
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName,
ValidatesOnDataErrors=True}"/>
在这里检索到:http://msdn.microsoft.com/en-us/library/ykdxa0bc (v =应用程序). 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;
}
基本上你可以使用条件语句来验证数据。
这显然是验证单元格中存在某些东西的最标准方法…