DataGridView 中的多列值搜索






4.46/5 (9投票s)
本文帮助搜索 DataGridView 所提供列的多个单元格值。
引言
这篇文章将帮助您在提供的列中搜索 datagridview
的多个单元格值。
“添加/删除”按钮在顶部的 datagridview
中添加/删除行,用户可以在其中输入搜索条件。
底部的 datagridview
是执行搜索的网格。
顶部 datagridview
的第一列列出了底部 datagridview
的所有列名。 用户必须在第二列中输入搜索值。
此属性从顶部的 datagridview
获取搜索条件
/// <summary>
/// Returns Dictionary(columnName, searchValue)
/// </summary>
private Dictionary<string, string> SearchList
{
get
{
Dictionary<string, string> searchList = new Dictionary<string, string>();
foreach (DataGridViewRow dgvRow in dataGridViewSearch.Rows)
{
string colName = Convert.ToString(dgvRow.Cells["ColumnName"].Value);
//ignore rows which have no "ColumnName" assigned
if (colName != string.Empty)
{
string val = Convert.ToString(dgvRow.Cells["Value"].Value);
searchList.Add(colName, val);
}
}
return searchList;
}
}
此例程执行搜索操作,并将匹配的 datagridviewrow
作为列表返回
/// <summary>
/// Perform Search in the provided datagridview
/// with the Dictionary(columnName, searchValue)
/// </summary>
/// <param name="dgView"></param>
/// <param name="searchList"></param>
/// <returns>List of rows which satisfy the search criteria</returns>
private List<DataGridViewRow> PerformSearch
(DataGridView dgView, Dictionary<string, string> searchList)
{
bool rowFound = false;
List<DataGridViewRow> dgvSearchResult = new List<DataGridViewRow>();
foreach (DataGridViewRow dgvRow in dgView.Rows)
{
foreach (string colName in searchList.Keys)
{
string val1 = Convert.ToString(dgvRow.Cells[colName].Value);
string val2 = Convert.ToString(searchList[colName]);
//Ignore case and compare values
if (string.Compare(val1, val2, true) == 0)
rowFound = true;
else
{
//Stop searching other cell values, if in the wrong row
rowFound = false;
break;
}
}
if (rowFound)
dgvSearchResult.Add( dgvRow);
}
return dgvSearchResult;
}
搜索按钮点击事件定义如下
private void btnSearch_Click(object sender, EventArgs e)
{
lblInfo.Text = string.Empty;
//Check if the search column Name repeats
List<string> colNameList = new List<string>();
foreach (DataGridViewRow dgvRow in dataGridViewSearch.Rows)
if (!colNameList.Contains(Convert.ToString(dgvRow.Cells["ColumnName"].Value)))
colNameList.Add(Convert.ToString(dgvRow.Cells["ColumnName"].Value));
else
{
MessageBox.Show("Invalid Search criteria", "Search",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//Perform search and get the result rows
List<DataGridViewRow> resultRows = PerformSearch(dataGridView1, SearchList);
//Deselect all Cells in the gridview
if (this.dataGridView1.SelectedCells.Count > 0)
foreach (DataGridViewCell dgvCell in this.dataGridView1.SelectedCells)
dgvCell.Selected = false;
if (resultRows.Count > 0)
{
//Select the rows which satisfy the search criteria
foreach (DataGridViewRow dgvRow in resultRows)
dataGridView1.Rows[dgvRow.Index].Selected = true;
}
lblInfo.Text = resultRows.Count.ToString() + " Match(s) Found";
}
附带的源代码是 VS 2010 的。
谢谢,
Balu