GridView中回车控制焦点以及DataGridView的焦点

本文介绍了如何在C#中利用GridView控件,通过回车键实现横向移焦点的功能,包括如何在DataGridView中保存焦点位置,并在按下Enter键时进行特定的操作,如添加新行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


     
    //回车切换焦点方法,只需在界面设置控件的TabIndex即可,以后用

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((!(ActiveControl is Button)) && (keyData == Keys.Up || keyData == Keys.Down || keyData == Keys.Enter))
            {
                if (keyData == Keys.Enter)
                {
                    System.Windows.Forms.SendKeys.Send("{TAB}");
                    return true;
                }
                if (keyData == Keys.Down)
                    System.Windows.Forms.SendKeys.Send("{TAB}");
                else
                    SendKeys.Send("+{Tab}");
                return true;
            }
            else
                return base.ProcessCmdKey(ref msg, keyData);
        }

  

     // GridView中回车横向移焦点,保存好些方法

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            enterkey = false;
            if (keyData == Keys.Enter)
            {
                if (this.dataGridView1.IsCurrentCellInEditMode)
                {
                    enterkey = true;
                    if (this.dataGridView1.CurrentCell.ColumnIndex < this.dataGridView1.ColumnCount - 1)
                    {
                        if (this.dataGridView1.CurrentCell.ColumnIndex == 5)
                        {
                            DataRow row = dt.NewRow();
                            row["ID"] = dt.Rows.Count + 1;
                            row["QrCode"] = "";
                            row["JiuKuanName"] = "";
                            row["ShuLiang"] = "0";
                            row["DanJia"] = "0";
                            row["JinE"] = "0";
                            dt.Rows.Add(row);//添加新行 
                            this.dataGridView1.DataSource = dt;
                            dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2];
                            return false; ;
                        }
                        else
                        {
                            this.dataGridView1.CurrentCell = this.dataGridView1[this.dataGridView1.CurrentCell.ColumnIndex + 3,this.dataGridView1.CurrentCell.RowIndex];

                        }
                    }
                }
            }

            return base.ProcessCmdKey(ref msg, keyData);

        }

转载于:https://www.cnblogs.com/chengpeng/archive/2011/11/09/2243711.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值