使用文本框搜索给定datagridview列中的值,下面的代码将所选行放在包含所键入文本的列上。
private void textBox1_TextChanged(object sender, EventArgs e)
{
//if (Char.IsLetter(e.KeyChar))
//{
for (int i = 0; i < (productDataGridView.Rows.Count); i++)
{
if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))
{
productDataGridView.FirstDisplayedCell = productDataGridView[1, i];
productDataGridView.CurrentRow.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
return; // stop looping
}
}
}
问题是我在文本框中输入时无法突出显示或更改所需行的背景颜色,有什么帮助吗?
答案 0 :(得分:0)
试试这个
//restore backcolor of rows to default e.g. loop through grid and set backcolor to white
foreach(DataGridViewRow row in productDataGridView.Rows)
{
if (row.Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))
{
//productDataGridView.FirstDisplayedCell = productDataGridView[1, i];
row.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
return; // stop looping
}
else
//Set backcolor to default
}
//return; //move return here
答案 1 :(得分:0)
试过这个解决方案,这最终就像一个魅力:
try
{
productDataGridView.ClearSelection(); //or restore rows backcolor to default
for (int i = 0; i < (productDataGridView.Rows.Count); i++)
{
if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))
{
productDataGridView.FirstDisplayedScrollingRowIndex = i;
productDataGridView.Rows[i].Selected = true; //It is also possible to color the row backgroud
return;
}
}
}
catch (Exception)
{
}