【问题标题】:Search for value in DataGridView in a column在 DataGridView 的列中搜索值
【发布时间】:2012-10-21 20:29:34
【问题描述】:

我希望用户能够在 DataGridView (dgv) 的列中搜索数字。 dgv 可以保存许多记录。每条记录都有一个项目编号。所以我希望用户能够在项目编号列中搜索项目编号。我拥有的列是:ProjectID(不可见);图片(无标题文本);项目编号;项目名;公司;联系方式。

这是我的代码:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;
    int rowIndex = -1;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dgvProjects.Rows[row.Index].Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

问题 #1: 到目前为止所做的事情:用户在 TextBox1 中键入项目编号。当他/她单击按钮时,代码会在行中搜索此字符串,并在找到项目编号时选择该行。它工作正常,但只有一次。当我想搜索其他项目编号时,没有任何反应。

问题 #2: 我认为这可以通过仅搜索列项目名称的值来以更好的方式完成。但是我应该如何正确地做到这一点呢?

我用来搜索的代码来自this answer

【问题讨论】:

    标签: c# winforms datagridview datagridviewcolumn


    【解决方案1】:
     private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string searchValue = txtSearch.Text;
                string colName = dataGridView1.Columns[1].Name;//Column Number of Search
                ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
          
        }
    
        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            btnSearch_Click(null,null);
        }
    

    【讨论】:

      【解决方案2】:

      最好也将你的逻辑分开在另一个方法中,或者在另一个类中。

      此方法将帮助您检索在其中找到文本的 DataGridViewCell 对象。

          /// <summary>
          /// Check if a given text exists in the given DataGridView at a given column index
          /// </summary>
          /// <param name="searchText"></param>
          /// <param name="dataGridView"></param>
          /// <param name="columnIndex"></param>
          /// <returns>The cell in which the searchText was found</returns>
          private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
          {
              DataGridViewCell cellWhereTextIsMet = null;
      
              // For every row in the grid (obviously)
              foreach (DataGridViewRow row in dataGridView.Rows)
              {
                  // I did not test this case, but cell.Value is an object, and objects can be null
                  // So check if the cell is null before using .ToString()
                  if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
                  {
                      // the searchText is equals to the text in this cell.
                      cellWhereTextIsMet = row.Cells[columnIndex];
                      break;
                  }
              }
      
              return cellWhereTextIsMet;
          }
      
          private void button_click(object sender, EventArgs e)
          {
              DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
              if (cell != null)
              {
                  // Value exists in the grid
                  // you can do extra stuff on the cell
                  cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
              }
              else
              {
                  // Value does not exist in the grid
              }
          }
      

      【讨论】:

        【解决方案3】:

        "MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

        数据库连接和数据表的关系如何?我应该如何正确设置 DefaultView?

        我使用这段代码来获取数据:

        con = new System.Data.SqlServerCe.SqlCeConnection();
        con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
        con.Open();
        
        DataTable dt = new DataTable();
        
        adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
        adapt.Fill(dt);        
        dataGridView1.DataSource = dt;
        con.Close();
        

        【讨论】:

        • 虽然您还没有评论的声誉,但这不是问题的答案
        【解决方案4】:

        直接从DataTableDataset过滤数据:

        "MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
           this.dataGridView1.DataSource = "MyTable".DefaultView;
        

        Textbox 的事件KeyUp 上使用此代码,将“MyTable”替换为您的表名或数据集,替换为您要进行搜索的字段。

        【讨论】:

          【解决方案5】:
          //     This is the exact code for search facility in datagridview.
          private void buttonSearch_Click(object sender, EventArgs e)
          {
              string searchValue=textBoxSearch.Text;
              int rowIndex = 1;  //this one is depending on the position of cell or column
              //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
          
              dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
              try
              {
                  bool valueResulet = true;
                  foreach (DataGridViewRow row in dataGridView1.Rows)
                  {
                      if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
                      {
                          rowIndex = row.Index;
                          dataGridView1.Rows[rowIndex].Selected = true;
                          rowIndex++;
                          valueResulet = false;
                      }
                  }
                  if (valueResulet != false)
                  {
                      MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
                      return;
                  }
              }
              catch (Exception exc)
              {
                  MessageBox.Show(exc.Message);
              }
          }
          

          【讨论】:

            【解决方案6】:

            你为什么不先建立一个DataTable,然后将它分配给DataGridView作为DataSource

            DataTable table4DataSource=new DataTable();
            
            table4DataSource.Columns.Add("col00");
            table4DataSource.Columns.Add("col01");
            table4DataSource.Columns.Add("col02");
            
            ...
            

            (手动添加行,在一个圆圈中或通过数据库表中的DataReader) (分配数据源)

            dtGrdViewGrid.DataSource = table4DataSource;
            

            然后使用:

            (dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
            dtGrdViewGrid.Refresh();
            

            您甚至可以将这段代码放入您的textbox_textchange 事件中,您的过滤值将在您编写时显示。

            【讨论】:

              【解决方案7】:

              为什么要使用 row.Cells[row.Index]。您需要指定要搜索的列的索引(问题 #2)。例如,您需要将 row.Cells[row.Index] 更改为 row.Cells[2] 其中 2 是您的列的索引:

              private void btnSearch_Click(object sender, EventArgs e)
              {
                  string searchValue = textBox1.Text;
              
                  dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                  try
                  {
                      foreach (DataGridViewRow row in dgvProjects.Rows)
                      {
                          if (row.Cells[2].Value.ToString().Equals(searchValue))
                          {
                              row.Selected = true;
                              break;
                          }
                      }
                  }
                  catch (Exception exc)
                  {
                      MessageBox.Show(exc.Message);
                  }
              }
              

              【讨论】:

              • 谢谢,我已经想到了类似的东西,但当时我使用了错误的值......这解决了两个问题
              • 是 dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;必要的?使用foreach循环还不够?
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-12-01
              • 1970-01-01
              • 2021-10-26
              • 2023-03-14
              • 2011-09-06
              • 2014-11-11
              相关资源
              最近更新 更多