仅在第一列(索引0)中显示单元格与特定日期匹配的行

时间:2013-12-12 14:53:46

标签: c# datagridview

如何隐藏dataGridView上与" 27/11 / 2013"的日期不匹配的所有行。目前,下面的代码隐藏了我的所有行...

private void viewOverdue_Click(object sender, EventArgs e)
{
    CurrencyManager manager = (CurrencyManager)BindingContext[dataGridView1.DataSource];
    manager.SuspendBinding();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
            if (!string.Equals(row.Cells[0].Value.ToString(), "27/11/2013", StringComparison.OrdinalIgnoreCase))
            {
                row.Visible = false;
            }
            else
            {
                row.Visible = true;
            }
    }
    manager.ResumeBinding();
}

1 个答案:

答案 0 :(得分:3)

您应该将DateTime解析为字符串然后进行比较。

DateTime dt = DateTime.ParseExact(row.Cells[0].Value.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string d = dt.ToString("dd/M/yyyy");
if (!string.Equals(d, "27/11/2013", StringComparison.OrdinalIgnoreCase)) {
    row.Visible = false;
}
else
{
    row.Visible = true;
}

还实现以下命名空间:

using System.Globalization;