2

我正在尝试使用以下代码过滤数据表

private void Filter(string text)
    {
        int outText=0;
        if (Int32.TryParse(text, out outText))
        {
            text = string.Empty;
        }
     DataTable DT = new DataTable();
            DT = PinCDAO.GetArea().AsEnumerable().Where(r => r.Field<int>("AreaID")==Convert.ToInt32(outText) || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();

}

我收到错误“指定的演员表无效”。因为代码

r => r.Field<int>("AreaID")==Convert.ToInt32(outText) 

我确定 AreaID 列包含整数

请帮我解决这个问题。

4

4 回答 4

2

Try out code - Handle null in you code

because "AreaID" is nullable field.

DT = PinCDAO.GetArea().AsEnumerable().Where(r => 
   (Convert.IsDBNull(r["AreaID"]) ? 0 :  Convert.ToInt32(r["AreaID"])) ==outText
  || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();

this code handles null value easily..

already answered question by me : "Specified cast is not valid" error in LINQ's orderby clause

于 2012-07-03T06:26:48.417 回答
1

You don't need conversion to int as outText already declared to int....You can simply use the outText in following way:

r => r.Field<int>("AreaID")==outText 

You can change the expresson in following way:

 r => Convert.ToInt32(r["AreaID"])==outText 
于 2012-07-03T06:25:30.923 回答
1

Variables passed as an out arguments need not be initialized prior to being passed. Moreover, outtext need not to be convert to Int32 as it is one already.

private void Filter(string text)     {      
   int outText;         
          if (Int32.TryParse(text, out outText))        
                  { 
                    // text was integer and parsed successfully.            
                    text = string.Empty;       
                   }     
 DataTable DT = new DataTable();  
           DT = PinCDAO.GetArea().AsEnumerable().Where(r => r.Field<int>("AreaID")== outText || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();  } 
于 2012-07-03T06:25:51.887 回答
1

删除 Convert.ToInt32,outText 已经被解析为 int 使用 if (Int32.TryParse(text, out outText))

DT = PinCDAO.GetArea().AsEnumerable()
          .Where(r => r.Field<int>("AreaID")==outText 
                           || (r.Field<string>("AreaDescription")
           .Contains(text))).AsDataView().ToTable();

您收到异常的原因可能是“AreaID”可能不包含 int 值

于 2012-07-03T06:22:32.670 回答