如何验证数据表行的值是否不小于零? [英] How to validate data table rows value is not less than zero?

查看:68
本文介绍了如何验证数据表行的值是否不小于零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if (ds.Tables [s] .Rows [i] [Columncountvalue] .ToString()。Trim()= =  
{
statement
}



i验证行如果是statement.now,我想验证数据表行是否小于或等于0(零)。

如何验证小于或大于行值。



我尝试过:



i使用下面的代码。但是显示无效的输入字符串错误。

 如果( ds.Tables [s] .Rows [i] [Columncountvalue] .ToString()。Trim()< 0   
{
语句
}

解决方案

那个空字符串方法会在整数值的情况下完美地为字符串工作,你应该将它转换为整数,例如,

  int   value ; 
if int .TryParse(ds.Tables [s] .Rows [i] [ Columncountvalue] .ToString(), out value )){
// 解析值,检查是否大于零
if value > = 0 ) {
// 这里的逻辑代码。
} else {
}
}



通过这种方式,您可以使用算术和算法来检查值。数字的逻辑运算。



另一方面,以下代码甚至不会编译:

 ds.Tables [s] .Rows [i] [Columncountvalue] .ToString()。Trim()< 0   



因为, 0是C#中的非法声明。有关更多信息,请访问: Int32.TryParse Method(String,Int32)(系统) [ ^ ]


解决方案1中的答案非常有效。但是为了给你另一个方面,如果场景是:

- 你正在使用具有相同结构的数据表的几个实例

- 如果你使用数据表数据网格或类似的示例

- 您希望在多个列之间进行验证等等

您可以将验证放在一个地方,数据表中。



例如,您可以创建特定于某些结构的数据表,并利用RowChanging事件进行验证。请考虑以下数据表定义

  ///   < span class =code-summarycomment><  摘要 >  
/// 特定用途的数据表
/// < / summary >
public class MyDataTable:DataTable {
/// < 摘要 >
/// 默认构造函数
/// < / summary >
public MyDataTable(): base (){
this .RowChanging + = MyDataTable_RowChanging;
this .Columns.Add( new DataColumn(){
ColumnName = < span class =code-string> IntegerColumn
AllowDBNull = false
DataType = typeof int
});
this .Columns.Add( new DataColumn(){
ColumnName = < span class =code-string> StringColumn
AllowDBNull = true
DataType = typeof string
});
}
/// < 摘要 >
/// 验证行
/// < / summary >
private void MyDataTable_RowChanging( object sender,DataRowChangeEventArgs e){
if (( int )e.Row [ IntegerColumn] < = 0 ){
e.Row.SetColumnError( this .Columns [ IntegerColumn], 值必须至少为1);
}
if (( int )e.Row [ IntegerColumn] > 10
&&(e.Row [ StringColumn] == DBNull.Value
|| string .IsNullOrEmpty(( string ) e.Row [ StringColumn]))){
e.Row.SetColumnError( this .Columns [ StringColumn] , 如果整数大于10,则必须为字符串列提供值;
}
}
}





现在每次将一行添加到数据表中RowChanging事件发生,允许对行进行验证。无论从哪里添加行,都会发生这种情况。如果直接通过网格添加行,则仍然会进行验证。



关于用法,请看下面的示例

 MyDataTable myTable =  new  MyDataTable(); 
DataRow行;

// 添加无效的行
行= myTable.NewRow();
row [ IntegerColumn] = -1;
myTable.Rows.Add(row);

row = myTable.NewRow();
row [ IntegerColumn] = 1 ;
myTable.Rows.Add(row);

// 添加无效的行
行= myTable.NewRow();
row [ IntegerColumn] = 22 ;
myTable.Rows.Add(row);

row = myTable.NewRow();
row [ IntegerColumn] = 22 ;
row [ StringColumn] = 一些文字;
myTable.Rows.Add(row);

// 该表将有4行,其中2行有错误
if (myTable.HasErrors){
foreach (DataRow errorRow in myTable.Rows){
if (errorRow.HasErrors){
foreach (DataColumn errorColumn in errorRow.GetColumnsInError()){
System.Diagnostics.Trace.WriteLine( string .Format( {0}:{1}
errorColumn.ColumnName,
errorRow.GetColumnError(errorColumn)));
}
}
}
}



另外一个好处是许多可绑定到数据表的控件,检查行是否有错误。在这种情况下,它们会自动突出显示向用户提供反馈的行。



示例快速编写,因此需要更多工作。在深入处理数据表中的事件之前,请阅读处理DataTable事件 [ ^


if (ds.Tables[s].Rows[i][Columncountvalue].ToString().Trim() == "")
{
   statement
}  


i validate rows is not empty above if statement.now i want to validate if the data table rows get less than or equal to 0(zero).
how to validate less than or greater than of rows value.

What I have tried:

i use below code.but shown invalid input string error occur.

if (ds.Tables[s].Rows[i][Columncountvalue].ToString().Trim() <0 "")
{
   statement
}

解决方案

That empty string method would work perfectly for strings in the case of integer values you should convert it to integer, like,

int value;
if(int.TryParse(ds.Tables[s].Rows[i][Columncountvalue].ToString(), out value)) {
   // value parsed, check if greater than zero
   if(value >= 0) {
      // Logic code here.
   } else {
   }
}


This way you will be able to check the value, using the arithmetical and logical operation of numbers.

And on the other hand, the following code won't even compile:

ds.Tables[s].Rows[i][Columncountvalue].ToString().Trim() <0 ""


Because, 0 "" is an illegal statement in C#. For more, please go through:
Int32.TryParse Method (String, Int32) (System)[^]


The answer in solution 1 works perfectly well. But to give you another aspect, if the scenario is:
- you're using several instances of a data table with same structure
- if you use the data table for example in data grid or similar
- you want to do validation between several columns and so on
You could possibly benefit from putting the validations into a single place, the data table.

For example you can create a data table specific for certain structure and utilize the RowChanging event to do the validation. Consider the following data table definition

/// <summary>
   /// Data table for specific usage
   /// </summary>
   public class MyDataTable : DataTable {
      /// <summary>
      /// Default constructor
      /// </summary>
      public MyDataTable() : base() {
         this.RowChanging += MyDataTable_RowChanging;
         this.Columns.Add(new DataColumn() {
            ColumnName = "IntegerColumn",
            AllowDBNull = false,
            DataType = typeof(int)
         });
         this.Columns.Add(new DataColumn() {
            ColumnName = "StringColumn",
            AllowDBNull = true,
            DataType = typeof(string)
         });
      }
      /// <summary>
      /// Validate the row
      /// </summary>
      private void MyDataTable_RowChanging(object sender, DataRowChangeEventArgs e) {
         if ((int)e.Row["IntegerColumn"] <= 0) {
            e.Row.SetColumnError(this.Columns["IntegerColumn"], "Value must be at least 1");
         }
         if ((int)e.Row["IntegerColumn"] > 10
            &&  (e.Row["StringColumn"] == DBNull.Value
               || string.IsNullOrEmpty((string)e.Row["StringColumn"]))) {
            e.Row.SetColumnError(this.Columns["StringColumn"], "String column must be provided with a value if integer is greater than 10");
         }
      }
   }



Now each time a row is added to the data table the RowChanging event takes place allowing to do validation for the row. This happens regardless from where the row is added. If the row is added directly via a grid, the validation still occurs.

About the usage, have a look at the following examples

MyDataTable myTable = new MyDataTable();
DataRow row;

// Add a row that will be invalid
row = myTable.NewRow();
row["IntegerColumn"] = -1;
myTable.Rows.Add(row);

row = myTable.NewRow();
row["IntegerColumn"] = 1;
myTable.Rows.Add(row);

// Add a row that will be invalid
row = myTable.NewRow();
row["IntegerColumn"] = 22;
myTable.Rows.Add(row);

row = myTable.NewRow();
row["IntegerColumn"] = 22;
row["StringColumn"] = "Some text";
myTable.Rows.Add(row);

// The table will have 4 rows and 2 of them have errors
if (myTable.HasErrors) {
   foreach (DataRow errorRow in myTable.Rows) {
      if (errorRow.HasErrors) {
         foreach (DataColumn errorColumn in errorRow.GetColumnsInError()) {
            System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}",
               errorColumn.ColumnName,
               errorRow.GetColumnError(errorColumn)));
         }
      }
   }
}


Also one benefit is that many controls that are bindable to a data table, check if the row has errors. In such case they automatically highlight the row providing feedback to the user.

The example is quickly written so it needs more work. Also before diving into handling events in data table, read through Handling DataTable Events[^]


这篇关于如何验证数据表行的值是否不小于零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆