使用文本框搜索DataGrid

时间:2015-04-21 09:09:56

标签: c# search datagrid

我一直在玩这个问题几个小时,似乎无法让它发挥作用。

似乎没有搜索行?

private void searchbutton_Click(object sender, EventArgs e)
    {
        string searchValue = searchtextBox.Text;
        int rowIndex = 0;

        inkGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {
            bool valueResulet = true;
            foreach (DataGridViewRow row in inkGridView.Rows)
            {
                if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
                {
                    rowIndex = row.Index;
                    inkGridView.Rows[rowIndex].Selected = true;
                    rowIndex++;
                    valueResulet = false;
                }
            }
            if (valueResulet != false)
            {
                MessageBox.Show("Unable to find "+ searchtextBox.Text,"Not Found");
                return;
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }

它总是抛出错误。

3 个答案:

答案 0 :(得分:1)

我为我使用的dataGridView创建了一个搜索文本框,所以这对你有用,因为控件非常相似。虽然我选择在找不到它时不给出消息。而不是它将文本框变为红色的消息,它也试图找到完整文本的第一个出现。如果找不到完全匹配,它将尝试查找包含搜索值的匹配

private void searchart()
{
  int itemrow = -1;
  String searchValue = cueTextBox1.Text.ToUpper();

  if (searchValue != null && searchValue != "")
    {
    foreach (DataGridViewRow row in dataGridView1.Rows)
      {
      //search for identical art
      if (row.Cells[0].Value.ToString().Equals(searchValue))
        {
          itemrow = row.Index;
          break;//stop searching if it's found
        }
      //search for first art that contains search value
      else if (row.Cells[0].Value.ToString().Contains(searchValue) && itemrow == -1)
      {
        itemrow = row.Index;
      }
    }
    //if nothing found set color red
    if (itemrow == -1)
    {
      cueTextBox1.BackColor = Color.Red;
    }
    //if found set color white, select the row and go to the row
    else
    {
      cueTextBox1.BackColor = Color.White;
      dataGridView1.Rows[itemrow].Selected = true;
      dataGridView1.FirstDisplayedScrollingRowIndex = itemrow;
    }
  }
}

答案 1 :(得分:0)

在我看来,你的if语句就是问题所在。即row.Cells[rowIndex]返回每行中的Cells,因此命名为rowIndex并在if语句中使用的实际上是列索引。所以你可以改成它,比如说:

if (row.Cells[0].Value.ToString().Equals(searchValue))

搜索第一列。要检查所有Cell列,必须在每行中循环它们。

您可能还想查看rowIndex的使用情况,因为您首先将其分配给0并在循环中启动它。但是,然后你将它分配给

  

rowIndex = row.Index;

然后继续增加(但只有在找到匹配项时)。我认为你的行和列索引混合在一起/交织在一起。

编辑:我认为抛出的异常是由于没有足够的列,因为你循环遍历单元格(0,0),(1,1),(2,2)......等等而不是循环在带有指定列的行上。

答案 2 :(得分:0)

我会说,除非您将DataGridView.AllowUserToAddRows设置为false,否则在尝试访问最后一行的Value.ToString()时,您将获得空引用异常。因此要么将其设置为false,要么添加新行,只需添加一个检查

if (row.IsNewRow) continue;
相关问题