当选择搜索行时,所选行将自动显示在gridviewrow顶部,并突出显示,之前的数据也会显示,但选择的行索引会更改。
问题是我在gridview中有1000行数据,当我可以搜索500行时,500行显示在gridview行的顶部,其他数据也显示在gridview中。
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToInt32(row.Cells[0].Value) == Convert.ToInt32(txt_empc.Text))
{
row.Selected = true;
//when search row selected then selected row show on top of gridviewrow
//automatically with highlighted and previous data also show but selected
//row index change
}
}
答案 0 :(得分:0)
您可以尝试这样做:将CurrentCell分配给已创建的行以使其显示第一个
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToInt32(row.Cells[0].Value) == Convert.ToInt32(txt_empc.Text))
{
row.Selected = true;
dataGridView1.CurrentCell = dataGridView1.Rows[row.Index].Cells[0];
break;
}
}
或使用linq更好:
foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => Convert.ToInt32(row.Cells[0].Value) == Convert.ToInt32(txt_empc.Text)))
{
row.Selected = true;
dataGridView1.CurrentCell = dgwDistinte.Grid.Rows[row.Index].Cells[0];
break;
}
答案 1 :(得分:0)
试试这段代码,但它不是一个优化的代码,如果您找到了一个更好的解决方案需要我自己进行优化,请告诉我!:/:!
List<DataGridViewRow>selectedRows = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToInt32(row.Cells[2].Value) == Convert.ToInt32(txt_empc.Text))
{
selectedRows.Add(row);
dataGridView1.Rows.Remove(row);
////when search row selected then selected row show on top of gridviewrow automatically with highlighted and previous data also show but selected row index change
}
row.Selected = false;
}
foreach (DataGridViewRow row in selectedRows)
{
dataGridView1.Rows.Insert(0,row);
dataGridView1.Rows[0].Selected = true;
}