'Searching in datagridview using c#
After loading a table in datagridview I'm generating a combobox's items from the datagrid column headers. From the combobox I am selecting the column and I have a textbox for the search value given by user. I'm using the following code:
string searchForText = txtCrudSearch.Text;
dgvLoadTable.ClearSelection();
dgvLoadTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvLoadTable.Rows)
{
if (row.Cells[cboCrudSearchColumn.SelectedIndex].Value.ToString().Equals(searchForText))
{
row.Selected = true;
//if I use break here the code doesn't give exception
//but highlights only one row. I want to return all rows that
// match with the search string
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Now , the problems are:
- I get all matched rows highlighted with the exception "Object reference not set to an instance of the object"
- How can I return all the matching rows only in the datagrid instead of highlighting them?
- The search is case sensitive, how to make it work for all types?
Any help will be appreciated, thanks.
Solution 1:[1]
I figured it out. In case anyone needs the solution, the code is as follows:
private void btnCrudSearch_Click(object sender, EventArgs e)
{
dgvLoadTable.CurrentCell = null;
dgvLoadTable.AllowUserToAddRows = false;
dgvLoadTable.ClearSelection();
dgvLoadTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgvLoadTable.ReadOnly = true;
try
{
foreach (DataGridViewRow row in dgvLoadTable.Rows)
{
var cellValue = row.Cells[cboCrudSearchColumn.SelectedIndex].Value;
if (cellValue != null && cellValue.ToString() == txtCrudSearch.Text.ToUpper())
{
row.Selected = true;
row.Visible = true;
}
else
row.Visible = false;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Solution 2:[2]
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearch.Text;
for (var i = 0; i <= dgvList.RowCount; i++)
{
for (var j = 0; j <= dgvList.ColumnCount; j++)
{
if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
{
Console.Writeline("found");
dgvList.Item(j, i).Selected = true;
return;
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | feather |
Solution 2 | Manoj Babu |