简体   繁体   English

DataView Rowfilter表达式C#

[英]DataView Rowfilter Expression C#

I am having a dataTable in which one of the columns is of a specific type of object say typeOf(A) - A being my custom class. 我有一个dataTable,其中的一列是特定类型的对象,例如typeOf(A)-A是我的自定义类。 The class A is having a text property and other properties like bool. 类A具有text属性和其他属性,如bool。 From user or external code I get only the text value to be used in RowFilter for Filtering, in the below example I will get "cat" as my filter to be used. 从用户或外部代码中,我仅获得要在RowFilter中进行过滤的文本值,在以下示例中,我将获得“ cat”作为要使用的过滤器。 Using this how to create the RowFilterExpression? 使用此如何创建RowFilterExpression?

class A
{
   public string Text{get;set;}
   public bool isReadonly {get;set;}
} 

DataTable table = new DataTable();
table.Columns.Add("col1", typeOf(A));
table.Rows.Add(new A{Text = "cat", isReadOnly = true,})
table.Rows.Add(new A{Text = "dog", isReadOnly = false,})

string filter = "cat";

DataView dataView = new DataView(table);
dataView.RowFilter = "[col1]='"+filter+"'";

The above expression doesnot work because it tries to match it to the object in cell. 上面的表达式不起作用,因为它试图将其与单元格中的对象匹配。 how to filter out the 1st row alone using this filter expression? 如何使用此过滤器表达式单独过滤出第一行?

Any help is appreciated. 任何帮助表示赞赏。

Try overriding ToString method in your object and then your current filtering code should work 尝试在您的对象中覆盖ToString方法,然后您当前的过滤代码应该可以正常工作

class A
{
   public string Text{get;set;}
   public bool isReadonly {get;set;}

   public override string ToString()
   {
      return this.Text;
   }
} 

overriding object ToString method like this : 像这样重写对象ToString方法:

class A
{
    public string Text { get; set; }
    public bool isReadonly { get; set; }

    public override string ToString()
    {
        return this.Text;
    }
}

and you can use : 您可以使用:

dataView.RowFilter = string.Format("Convert([col1], 'System.String') = '{0}'", filter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM