在C#中更改dataGridView单元格的焦点

时间:2015-01-27 07:21:26

标签: c# datagridview

我在c#中有dataGridview用于采购订单输入。我想在选择ItemId后按Enter键时将单元格Focus从 ItemId 更改为 NoofQty 。然后再次按Enter键转到下一行 ItemId

哪个dataGridview事件适合这个?你能不能请任何人帮助我.. 我尽可能地尝试如下 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);
        }
    }

2 个答案:

答案 0 :(得分:1)

试试这个:

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

OR

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

答案 1 :(得分:0)

 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);
        }
    }

根据@Pranav-BitWiser Guidance ...

,此代码可以正常工作