Veeramani Bala
Veeramani Bala

Reputation: 234

Change Focus of dataGridView cell in C#

I have the dataGridview in c# for Purchase order entry. I want to change the cell Focus from ItemId to NoofQty when I press Enter key after selecting ItemId. Then again press Enter key go to next row ItemId.

Which dataGridview event is suitable for this? Could you please anyone help me.. I have tried as far as I can as below enter image description here

  private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if(e.ColumnIndex==0)// ItemId
            {
                dataGridView1.Rows[e.RowIndex].Cells[4].Selected= true;
                dataGridView1.Rows[e.RowIndex].Cells[4].Value="1";
                //I want to edit this cell value
            }
            else if (e.ColumnIndex == 4)// ItemId
            {
                //goto next row and cell is ItemId
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Upvotes: 0

Views: 7635

Answers (2)

Veeramani Bala
Veeramani Bala

Reputation: 234

 private void Form1_Load(object sender, EventArgs e)
    {
        DataGridViewComboBoxColumn cmb = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];          
        cmb.Name = "cmb";
        cmb.MaxDropDownItems = 4;
        int no = 1001;
        for (int i = 0; i < 100; i++)
        {
            no++;
            cmb.Items.Add(no.ToString());
        }            
        dataGridView1.RefreshEdit();
        dataGridView1.Rows.Add();

    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if(e.ColumnIndex==0)// ItemId
            {

                dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[4];
                dataGridView1.CurrentCell.Value = "1";
                dataGridView1.BeginEdit(true);                    
            }
            else if (e.ColumnIndex == 4)// NoofQty
            {
                dataGridView1.Rows.Add();
                dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex+1].Cells[0];
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

This code works fine as per @Pranav-BitWiser Guidance ...

Upvotes: 0

Pranav Bilurkar
Pranav Bilurkar

Reputation: 965

Try this:

DataGridViewRow selectedRow = myGridView.Rows[rowToSelect];
selectedRow.Selected = true;
selectedRow.Cells[columnToSelect].Selected = true;

OR

myGridView.CurrentCell = myGridView.Rows[index].Cells[4];
myGridView.BeginEdit(true);

Upvotes: 2

Related Questions