在DataGridView中搜索匹配或部分匹配

时间:2011-08-08 22:13:18

标签: c# .net linq datagridview

试图筛选谷歌搜索结果;没运气。我正在尝试做的是,给出TextBox中的一些文本:在我的DataGridView的任何列中搜索至少部分匹配,并让控件选择第一行(将其显示为顶行并突出显示)它遇到了部分匹配。

这是我对DataGridView的DataSource的声明以及列的组织方式:

 var queryData = from va in xdoc.Descendants("language")
                    select new
                    {
                        StringID = va.Parent.Parent.Attribute("id").Value,
                        Language = va.Attribute("name").Value,
                        LanguageData = va.Element("value").Value,
                    };

        var organizedData = from x in queryData
                     group x by x.StringID into xg
                     select new
                     {
                         StringID = xg.Key,
                         English = xg.SingleOrDefault(x => x.Language == "ENGLISH_US").LanguageData,
                         Custom = xg.SingleOrDefault(x => x.Language == languageBox.SelectedItem.ToString()).LanguageData,
                     };

        mainView.DataSource = organizedData.ToList();

以下是处理点击“搜索”按钮的函数的当前定义:

private void searchButton_Click(object sender, EventArgs e)
    {
        int currentIndex = mainView.CurrentRow.Index;

        if (searchBox.Text.Length == 0)
        {
            mainView.CurrentCell = mainView[0,0];
            mainView.Focus();
            return;
        }
    }

1 个答案:

答案 0 :(得分:1)

这样的事可能会让你接近:

string searchForText = "whatever";

DataGridViewRow rowFound = mainView.Rows.OfType<DataGridViewRow>()
  .FirstOrDefault(row => row.Cells.OfType<DataGridViewCell>()
      .Any(cell => ((dynamic)cell.Value).StringID.Contains(searchForText)));

if (rowFound != null) {
    mainView.Rows[rowFound.Index].Selected = true;
    mainView.FirstDisplayedScrollingRowIndex = rowFound.Index;
}