【问题标题】:Check if DataGridView Contains specific word检查 DataGridView 是否包含特定单词
【发布时间】:2017-11-10 23:01:34
【问题描述】:

我目前正在做一个学校项目,我需要知道如何检查 datagridview 的任何行中是否在任何列中包含特定单词,并在任何列中隐藏不包含该单词的行。 我还没有代码,只有 datagridview 和表单上的文本框。

【问题讨论】:

  • 为什么不在 sql 中过滤
  • 这是您要找的吗? stackoverflow.com/questions/5843537/…
  • @BhubanShrestha,因为目标是用所有内容填充 datagridview,如果用户想要,他将能够过滤以轻松找到一些记录
  • 简单的方法是使用 linq 过滤网格视图数据源(数据表)并将过滤后的结果重新分配给网格视图的数据源
  • @BhubanShrestha 问题是我不知道该怎么做:\你能给我代码吗?

标签: c# datagridview


【解决方案1】:

您只想在文本框不为空或非空字符串时进行过滤(确保修剪字符串以删除前导和尾随空格)。

 (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("columnname like '%{0}%'", textBoxFilter.Text);
  • 过滤表达式

    • columnname like '%{0}%' 表示列名包含特定的单词/字符串。
    • columnname not like '%{0}% 表示不包含

【讨论】:

    【解决方案2】:

    我假设您将DataTable 用作DataSource

    当你传递TextBox.Textas RowFilter 并清除它时,它变成一个空字符串。

    TextChanged 事件中,只需检查TextBox 是否为空。您的活动将如下所示:

    private void textBoxFilter_TextChanged(object sender, EventArgs e)
    {
        if(!string.IsNullOrWhiteSpace(textBox1.Text))
        {
            (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要迭代所有行和单元格, 如果在单元格中找到您的关键字,则隐藏该行,

      private void HideRow(string word)
      {
          foreach (DataGridViewRow row in dataGridView1.Rows)
          {
              foreach (DataGridViewCell cell in row.Cells)
              {
                  var value = Convert.ToString(cell.Value);
                  if (word != value)
                  {
                      row.Visible = false;
                      break;
                  }
              }
          }
      }
      

      TextChanged 事件或ButtonClick 上随时随地调用此方法

      【讨论】:

      • Row.visible = false 会导致 Currencymanager 异常。您想先将 .Currentcell 设置为 NULL。
      猜你喜欢
      • 2016-08-19
      • 2011-10-28
      • 2013-12-23
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多