如何使用 RowFilter 过滤 GridView 中的数字和日期?

How to filter number and date in GridView using RowFilter?

我正在使用 C# 开发 Web 应用程序。我想通过从列表框中选择一列来过滤 GridView,然后根据用户使用 RowFilter 在文本框中键入的文本立即过滤 table。

我几乎已经完成了整个部分,但我一直在尝试解决数字和日期的比较问题。

文本比较效果很好:

DataTable dt = new DataTable();
dt = GridView1.DataSource as DataTable;
dt.DefaultView.RowFilter = string.Format(ListBox1.SelectedItem.Text + " LIKE '%{0}%'", textBox1.Text);

对于数字,我尝试了这样的方法(没有用):

dt.DefaultView.RowFilter = string.Format(ListBox1.SelectedItem.Text + " = '#{0}#'", textBox1.Text);

我想数字和日期的比较与文本的比较差不多吧?

请看DataView RowFilter Syntax

这些是 DataGridView 上带有字符串、数字和日期的 RowFilter 的语法规则。

字符串

dataView.RowFilter = "Name = 'John'"        // string value
dataView.RowFilter = "Name = 'John ''A'''"  // string with single quotes "John 'A'"
dataView.RowFilter = String.Format("Name = '{0}'", "John 'A'".Replace("'", "''"));

数字

dataView.RowFilter = "Year = 2008"          // integer value
dataView.RowFilter = "Price = 1199.9"       // float value
dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,
                     "Price = {0}", 1199.9f);

日期

dataView.RowFilter = "Date = #12/31/2008#"          // date value (time is 00:00:00)
dataView.RowFilter = "Date = #2008-12-31#"          // also this format is supported
dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value
dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
                     "Date = #{0}#", new DateTime(2008, 12, 31, 16, 44, 58));

我认为以下内容对您有所帮助...

        string colname = ListBox1.SelectedItem.Text;
        string value = textBox1.Text;
        if (colname != null && dt.Columns[colname] != null)
        {
            if ("Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(dt.Columns[colname].DataType.Name + ","))
            {
                dv.RowFilter = colname + "=" + value;
            }
            else if (dt.Columns[colname].DataType == typeof(string))
            {
                dv.RowFilter = string.Format(colname + " LIKE '%{0}%'", value);
            }
            else if (dt.Columns[colname].DataType == typeof(DateTime))
            {
                dv.RowFilter = colname + " = #" + value + "#";
            }
        }