DataGridView查找字符串 [英] DataGridView Find String
本文介绍了DataGridView查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在所有数据网格视图中找到一个字符串。
要做到这一点,我可以创建一个每个单元格迭代单元格的所有值的字符串缓冲区。
但我想知道如何使用带有字符串作为参数的Contain函数。
谢谢你,对不起我的基本英语haha
Hi,
I'm trying to find a string in all my datagridview.
To do it, I can creat a string buffer of all its values iterating cell per cell.
But I wonder how could I use the "Contain" function with a string as argument.
Thank you and sorry for my rudimentary english haha
推荐答案
如果你的目的是找到Cell
在包含给定Text
的DataGridView
中,我认为最好使用行
和Cells
DataGridView
的集合,用于生成包含给定文本的DataGridViewCell列表。然后在按钮上单击将CurrentCell
的DataGridView
设置为找到的单元格,如下所示:
If your purpose is to find theCell
in theDataGridView
containing a givenText
, then I think it is better to use theRows
andCells
collection ofDataGridView
to generate a List of DataGridViewCell which contain the given text. Then on a button click set theCurrentCell
ofDataGridView
to the found cells as shown below:
//Declare a List at Class level to hold the containing cells
//and an index to hold the current containing cell
List<datagridviewcell> containingCells = new List<datagridviewcell>();
int currentContainingCellListIndex = 0;
//In Event handler of Find button iterate all the rows and cells in
//each row to find the cells containing the required text
//if found add that to the containingCells List
ButtonFindText.Click += (sender, args) => {
containingCells.Clear();
currentContainingCellListIndex=0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value == DBNull.Value || cell.Value == null)
continue;
if (cell.Value.ToString().Contains(textToFind)) {
containingCells.Add(cell);
}
}
}
if (containingCells.Count > 0)
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
//In the Event handler of FindNext button set the next containingCell as
//the current cell of DataGridView
ButtonFindNext.Click += (sender, args) => {
if (currentContainingCellListIndex < containingCells.Count ())
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
//Find using LINQ
FindUsingLinqButton.Click += (sender, args) => {
currentContainingCellListIndex=0;
containingCells = dataGridView1.Rows.OfType<DataGridViewRow>().SelectMany (
dgvr => dgvr.Cells.OfType<DataGridViewCell>().Where (dgvc =>
dgvc.Value != DBNull.Value && dgvc.Value != null &&
dgvc.Value.ToString().Contains(textToFind))).ToList();
//If query syntax is required
//containingCells = (from row in dataGridView1.Rows.OfType<DataGridViewRow>()
// from cell in row.Cells.OfType<DataGridViewCell>()
// where cell.Value != DBNull.Value && cell.Value != null &&
// cell.Value.ToString().Contains("S")
// select cell).ToList();
if (containingCells.Count > 0)
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
}
这篇关于DataGridView查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文