winforms C#中的可编辑DataGridView

wb1gzix0  于 2023-05-29  发布在  C#
关注(0)|答案(1)|浏览(187)

我已经为我的项目创建了一个自定义DataGridview。我试图找到一种方法,当我的datagridview得到焦点时,它应该进入可编辑模式。我的意思是它的第一个单元格的第一个单元格应该进入可编辑模式。为了达到这个目的我需要做什么修改。

public partial class CustomControl1: DataGridView
{
    public CustomControl1()
    {
        this.KeyDown += new KeyEventHandler(CustomDataGridView_KeyDown);
        InitializeComponent();
    }
    protected override bool ProcessKeyPreview(ref Message m)
    {
        KeyEventArgs args1 = new KeyEventArgs(((Keys)((int)m.WParam)) | Control.ModifierKeys);
        switch (args1.KeyCode)
        {
            case Keys.Left:
            case Keys.Right:
            case Keys.Up:
            case Keys.Down:
                return false;
        }
        return base.ProcessKeyPreview(ref m);
    }      

   protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            this.CommitEdit(DataGridViewDataErrorContexts.Commit);
            this.EndEdit();

            int row = this.CurrentCell.RowIndex;
            int col = this.CurrentCell.ColumnIndex;
            if (col == 0 && string.IsNullOrEmpty(this.CurrentCell.Value?.ToString()))
            {
                this.SelectNextControl(this, true, true, true, true);
                return true;
            }
           else if (col == this.ColumnCount - 1) // CHECK IF I AM AT LAST COLUMN 
            {
                if (row == this.RowCount - 1)// CHECK IF I AM AT LAST ROW  
                {
                    this.Rows.Add();
                    this.CurrentCell = this[0, row + 1];
                    this.BeginEdit(true);
                    return base.ProcessDialogKey(keyData);
                }
                else
                {
                    this.CurrentCell = this[0, row + 1];                        
                }
            }
            else // not at last column 
            {
                this.CurrentCell = this[col + 1, row]; // change column
                this.BeginEdit(true);
            }
            return true;
        }
        return base.ProcessDialogKey(keyData);

    }
1rhkuytd

1rhkuytd1#

感谢@jimi
代码是

protected override void OnEnter(EventArgs e)
    {
        this.CurrentCell = this.Rows[0].Cells[0];
        this.BeginEdit(true);
       base.OnEnter(e);
    }

相关问题