dataGridView prevent relocation when updating

3

My program contains a dataGridView where a series of data is displayed, this is updated every X seconds with a Timer_tick , the problem is that in each update the selected row of DataGridView is again the first, the objective would be if I am in the middle of the table, do not climb up to the top losing the visualization of the data that interests me.

Selection method;

    private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e
    {

        try
        {
            id = Int32.Parse(dataGridView1.CurrentRow.Cells["id_curso"].Value.ToString());
            row = dataGridView1.CurrentRow.Index;

            datos[0] = dataGridView1.CurrentRow.Cells["titulo"].Value.ToString();//todos los datos del dataGrid y mostrar los datos en los txt correspondientes
            datos[1] = dataGridView1.CurrentRow.Cells["cod_curso"].Value.ToString();
            datos[2] = dataGridView1.CurrentRow.Cells["descripcion"].Value.ToString();
            datos[3] = dataGridView1.CurrentRow.Cells["horas"].Value.ToString();
            datos[4] = dataGridView1.CurrentRow.Cells["id_curso"].Value.ToString();
            txtTitulo.Text = datos[0];
            txtCodcurso.Text = datos[1];
            txtDescripcion.Text = datos[2];
            txtHoras.Text = datos[3];
        }
        catch (System.NullReferenceException) {

            MessageBox.Show("Los datos de este curso estan corruptos y no se pueden visualizar"); }
    }

Event Timer_tick:

    public override async void Timer1_Tick(object sender, EventArgs e)
    {

        Console.WriteLine("DataGridView actualizado");
        var list = await Task.Run(async () =>
        {
            return await _api.ObtenerCursos(string.Empty);
        });
        dataGridView1.DataSource = list;
        dataGridView1.ClearSelection();

        try
        {
            dataGridView1.Rows[row].Cells[0].Selected = true;
            //dataGridView1.Rows[row].Selected = true;
        }
        catch (System.ArgumentOutOfRangeException) { }

    }
    
asked by Hector Lopez 11.01.2018 в 10:39
source

1 answer

3

Once you have selected the row you had selected before updating, you should put the instruction FirstDisplayedScrollingRowIndex so that the DataGridView scroll to the index you indicate (which is the row you had selected), as follows:

    try
    {
        dataGridView1.Rows[row].Cells[0].Selected = true;
        //dataGridView1.Rows[row].Selected = true;
        dataGridView1.FirstDisplayedScrollingRowIndex = row;
    }
    catch (System.ArgumentOutOfRangeException) { }
    
answered by 11.01.2018 / 11:27
source