如何在刷新数据视图后保持在相同的单元格c#

本文关键字:单元格 刷新 数据 视图 | 更新日期: 2023-09-27 18:08:52

我使用定时器刷新datagridview。请帮帮我每10秒刷新一次datagridview。我找不到代码,在刷新或排序数据视图后,所选单元格将保持,请帮助我..

private void timer1_Tick(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {  
            SqlCommand cmd = new SqlCommand("SELECT (Cust_No) as [Customer ID],(Cust_surname) as [Surname], (Cust_fname) as [First Name], (Cust_mi) as [Middle Initial],  (Cust_address) as [Address], (Cust_ContactNO) as [Contact Number], (Cust_Faxno) as [Fax Number], (Cust_Tin)as [TIN]  FROM Customer WHERE cust_status like ('Active')");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet("ds");
            da.Fill(ds);
            ds.Tables[0].TableName = "table_mirror";
            dataGridView2.DataSource = ds.Tables["table_mirror"];
        }
        else
        {
            SqlCommand cmd1 = new SqlCommand("SELECT (comp_no) as [Company ID],(comp_name) as [Company Name], (comp_contactperson) as [Contact Person], (comp_address) as [Address],  (comp_contactno) as [Contact No], (comp_fax) as [Fax], (comp_Tin) as [Tin] FROM Company WHERE comp_status like ('Active')");
            cmd1.CommandType = CommandType.Text;
            cmd1.Connection = conn;
            da = new SqlDataAdapter(cmd1);
            ds = new DataSet("ds");
            da.Fill(ds);
            ds.Tables[0].TableName = "table_mirror";
            dataGridView2.DataSource = ds.Tables["table_mirror"];
        }
    }

如何在刷新数据视图后保持在相同的单元格c#

我想这对你有帮助。

        Point[] oldSelectedCells = new Point[dataGridView1.SelectedCells.Count];
        for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
        {
            oldSelectedCells[i].X = dataGridView1.SelectedCells[i].ColumnIndex;
            oldSelectedCells[i].Y = dataGridView1.SelectedCells[i].RowIndex;
        }
        // refresh datagridview
        dataGridView1.CurrentCell = null;
        foreach (Point p in oldSelectedCells)
            dataGridView1[p.X, p.Y].Selected = true;