我在七个不同的标签中有一个或两个datagridviews。我有一个搜索框,只是在当前选定的选项卡中搜索datagridview时工作正常,但是在多个选项卡中搜索已证明是一个问题。第一次使用搜索时,没有任何反应。之后,当找到要搜索的子字符串时,会显示正确的选项卡,但不会突出显示包含子字符串的行。如果我再次搜索而不更改标签页,则会突出显示正确的行...请提前感谢您的帮助!以下是我的方法:
private void searchBox_KeyDown(object sender, KeyEventArgs e)
{
// Declare DGV
DataGridView DGV = null;
bool isFound = false;
int tabIndex = -1;
// When a key is pressed and it's the enter key...
if (e.KeyCode == Keys.Enter)
{
// Loop through all tab pages
for (int i = 0; i < tabs.TabCount; i++)
{
// Loop through all controls in the selected tab
foreach (Control c in tabs.TabPages[i].Controls)
{
// if the control is a datagridview, cast it as a datagridview,
// and set DGV equal to it
if (c is DataGridView)
{
DGV = (DataGridView)c;
string name = DGV.Name;
// Pass in DGV to Search() to search all cells within it for
// the term in the searchbox
isFound = Search(DGV);
}
if (isFound)
tabIndex = i;
}
}
if (tabIndex >= 0)
{
tabs.SelectTab(tabIndex);
tabs.SelectedTab.Show();
highLightSearchRows();
}
}
}
这是我的搜索方法:
private bool Search(DataGridView dataGrid)
{
int i, j;
bool retval = false;
// Makes sure searchBox contains text before searching
if (searchBox.TextLength <= 0)
return false;
string searchBoxText = searchBox.Text, sub1 = searchBox.Text.Substring(1);
// Doesn't accept an empty string as a valid search parameter
if (searchBoxText == "")
return false;
string searchForText = searchBoxText;
// Starts looping from the bottom of the grid up
// This makes FirstDisplayedScrollingRowIndex show the uppermost match in the grid
for (i = dataGrid.Rows.Count - 1; i >= 0; i--)
{
// If any cells contain the search string, they are highlighted
if (dataGrid.Rows[i].Cells.OfType<DataGridViewCell>()
.Any(cell => ((dynamic)cell.Value).Contains(searchForText)))
retval = true;
// Deselect all rows in all datagrids in order for other rows to
// be programmatically selected
dataGrid.Rows[i].Selected = false;
}
return retval;
}
高亮行方法:
private void highLightSearchRows()
{
DataGridView DGV = null;
int rowIndex = -2;
foreach (Control c in tabs.SelectedTab.Controls)
{
// if the control is a datagridview, cast it as a datagridview,
// and set DGV equal to it
if (c is DataGridView)
{
DGV = (DataGridView)c;
string name = DGV.Name;
foreach (DataGridViewRow row in DGV.Rows)
{
// If any cells contain the search string, they are highlighted
if (row.Cells.OfType<DataGridViewCell>()
.Any(cell => ((dynamic)cell.Value).Contains(searchBox.Text)))
{
// Makes selected row the top row in the view
rowIndex = row.Index;
row.Selected = true;
DGV.FirstDisplayedScrollingRowIndex = rowIndex;
}
if (rowIndex >= 0)
{
// Select the matching row
row.Selected = true;
rowIndex = -2;
}
}
}
}
}