Home > Mobile >  How to move to previous Row in DataGridView using Button Click
How to move to previous Row in DataGridView using Button Click

Time:04-17

I have the following problem. I have a datagridview and would like to use a button press to go to the previous row based on the selected row. means line 10 is selected and when the button is clicked it should select line 9.

From Row 0 to the last row works. When i select an other row (row 10 or whatever) and press the button nothing happend. I hope you can help me.

 public Form1()
    {
        InitializeComponent();
    }

    private int number_of_rows;
    private int selected_row;

    private void Button_previous_Click(object sender, EventArgs e)
    {
        number_of_rows = dataGridView1.Rows.Count; // Rowcount
        if (number_of_rows > 0)
        {
            selected_row = dataGridView1.CurrentRow.Index;
            if (selected_row > 0)
            {
                dataGridView1.Rows[selected_row].Selected = false;
                selected_row = selected_row--;
                dataGridView1.Rows[selected_row].Selected = true;
            }
            else
            {
                dataGridView1.Rows[selected_row].Selected = false;
                selected_row = number_of_rows - 1;                    
                dataGridView1.Rows[selected_row].Selected = true;
            }
        }           
    }

CodePudding user response:

Best way to handle moving row to row in a DataGridView is by using a BindingSource and BindingNavigator. Set the DataSource property of the data to view in the DataGridView to the BindingSource, add a BindingNavigator and set the DataSource property to the BindingSource.

The following screenshot has a BindingNavigator at the top. See the enter image description here

Also note, without a BindingNavigator you can use methods of the BindingSource e.g. MoveNext for instance to change the selected DataGridView row.

CodePudding user response:

Thank you for your help. I will inform myself about the use of BindingNavigator/BindingSource. Thanks for the hints =) I have solved it as follows for now.

number_of_rows = dataGridView1.Rows.Count; // Rowcount
        if (number_of_rows > 0)
        {
            selected_row = dataGridView1.SelectedRows[0].Index;
            if (selected_row > 0)
            {
                dataGridView1.Rows[selected_row].Selected = false;                    
                selected_row = --selected_row;                    
                dataGridView1.Rows[selected_row].Selected = true;                    
            }
  • Related