Hi Kalaz.Net,
You can use binary search to speed up searching. This is the code snippet:
//Search class, assume the sort type is ascending.
public static class QuickSearch
{
public static int Search(DataGridView grid, int sortedColumnIndex, string startString)
{
int start = 0;
int end = grid.Rows.Count - 1;
return Search(grid, sortedColumnIndex, startString, start, end);
}
private static int Search(DataGridView grid, int sortedColumnIndex, string startString, int start, int end)
{
//Not found
if (string.IsNullOrEmpty(startString) || start > end) return -1;
//Get the string of the middle cell.
int midPos = (start + end) / 2;
object cellVal = grid[sortedColumnIndex, midPos].Value;
string cellString = cellVal == null ? "" : cellVal.ToString().Trim();
//Handle start == end
if (start == end)
return cellString.StartsWith(startString) ? start : -1;
//Handle blank.
if(cellString == "")
{
if(start < end)
{
//Search in the follow items.
return Search(grid,sortedColumnIndex,startString,start + 1, end);
}
else
return -1;//Not found.
}
if (cellString.Length >= startString.Length)
{
cellString = cellString.Substring(0, startString.Length);
int diff = cellString.CompareTo(startString);
if (diff == 0)
return midPos;//This means cellString starts with startString.
else if (diff > 0)
//cellString > startString, search in the first half.
return Search(grid, sortedColumnIndex, startString, start, midPos - 1);
else
//cellString < startString, search in the last half.
return Search(grid, sortedColumnIndex, startString, midPos + 1, end);
}
else
{
string newStartString = startString.Substring(0, cellString.Length);
int diff = newStartString.CompareTo(cellString);
if (diff >= 0)
//startString > cellString, search in the last half.
return Search(grid, sortedColumnIndex, startString, midPos + 1, end);
else
//startString < cellString, search in the first half.
return Search(grid, sortedColumnIndex, startString, start, midPos - 1);
}
}
}
Let me know if this helps.
Aland Li
Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.