-5

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.

问题是当我可以搜索 500 行时,我在 gridview 中有 1000 行数据,因此 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
    }
}
4

2 回答 2

0

试试这个代码,但它不是一个优化的代码,你自己优化了它,如果你找到了更好的解决方案,请告诉我,我需要 10 分钟!:/:!

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;
            }
于 2013-04-29T16:54:42.227 回答
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;
}
于 2013-04-29T15:19:51.730 回答