如何锁定dataGridView的实际水平位置

How to lock actual horizontal position of dataGridView

我正在使用 MySqlConnector 并执行查询以为 dataGridView 提供数据源。

SELECT 查询 returns 多行,每 10 秒刷新一次。我想在更新时“锁定滚动”。

当我在 UI 中向下滚动时,它会在更新数据源后回到顶部。我希望它在更新后处于相同位置。

它在另一个线程中有刷新无效,绑定源在另一个无效中被指定为数据源,在表单启动时执行。

void refresh()
    {
        Thread.Sleep(10000);
        for (;;)
        {
            conn.Open();
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT * FROM `table`";
            MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
            
            DataTable ds = new DataTable();
            adap.Fill(ds);
            
            SafeUpdate(() => bindingSource1.DataSource = ds);
            
            conn.Close();
        }
    }



void startup()
    {
        conn.Open();
        MySqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "SELECT * FROM `table`";
        MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
                
        DataTable ds = new DataTable();
        adap.Fill(ds);
        bindingSource1.DataSource = ds;
        dataGridView1.DataSource = bindingSource1;

        conn.Close();
    }

如果您当前的代码有效(我对此提出质疑)并且您可以滚动网格中的行,那么,如果您希望在网格数据源完成后在网格可视区域中显示当前“显示”的单元格“刷新”,那么您可能想在“刷新”网格数据源“之前”获取网格 FirstDisplayedScrollingRowIndex……然后“刷新”网格数据源后,将网格 FirstDisplayedScrollingRowIndex 设置为之前抓取的索引。像……

int curIndex = dataGridView1.FirstDisplayedScrollingRowIndex;
Refresh grids data source();
if (curIndex < dataGridView1.Rows.Count) {
  dataGridView1.FirstDisplayedScrollingRowIndex = curIndex;
}