Reputation: 23
Can anyone help me to find a string in the word, i.e, how to search any part of the name in datagridview? for eg. RamGopalVarma, if i type only varma in search option it should find in gridview.
Below is my code which is working only when I give total name. When I change "Equals" into "Contains" it's not working.
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.ClearSelection();
// Code to search the alphanumneric Part Number (in Column1 header called "Name") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["Name"].Value.ToString().Equals(textBox3.Text, StringComparison.CurrentCultureIgnoreCase))
{
dataGridView1.Rows[row.Index].Selected = true;
dataGridView1.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
Upvotes: 0
Views: 968
Reputation: 1041
The issue is the .Equals method has an option to ignore case, whereas the .Contains method is case-sensitive. You could try something like:
if (row.Cells["Name"].Value.ToString().ToUpperInvariant().Contains(textBox3.Text.ToUpperInvariant()))
{
// do something
}
If it were me, I'd perform convert textBox3 text to upper only once, before the loop.
Upvotes: 0
Reputation: 4542
Try this Pravii
if (row.Cells["Name"].FormattedValue.ToString().Contains(textBox1.Text))
or search all cells...
foreach (DataGridViewRow r in dataGridView1.Rows)
{
foreach (DataGridViewCell c in r.Cells)
{
if(c.FormattedValue.ToString().Contains(textBox1.Text))
{
//do your work.....
}
}
}
Try this pravii
if(c.FormattedValue.ToString().ToLower().Contains(textBox1.Text.ToLower()))
Upvotes: 1
Reputation: 9322
Why not use Contains like:
if (row.Cells["Name"].Value.ToString().Contains(textBox3.Text))
{
...the rest of the code if match
}
Upvotes: 0