winform控件重写方法

如DataGridView中的按Enter,默认的会跳到下一行。我想在DataGridView中按Enter能把某个单元格的值传到另一个窗体的TextBox。

1.把我的 DataGridView拖放在form中提中。

2.新建一个类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Hairdressing.SellDetailFile
{
    public sealed class MyDataGridView : DataGridView
    {
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                this.OnKeyPress(new KeyPressEventArgs('r'));
                return true;
            }
            else
                return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}

该类派生于 DataGridView

3. 打开Form1.Designer.cs文件,你会看到有这么一行。
private System.Windows.Forms. DataGridView:dataGridView1;
修改为
private MyDataGridView dataGridView1 ;
4. 再找到this. dataGridView1 = new System.Windows.Forms. DataGridView ();
修改为this. dataGridView1 = new MyDataGridView ();

然后编译,运行,此时窗体上的这个控件就是 MyDataGridView 类创造出来的了。

5.为datagridview1添加一个KeyPress事件,代码如下:

private void dgvCommodity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar=='r')
            {
                if (dgvCommodity.Rows.Count > 0)
                {
                    BCode = dgvCommodity.SelectedRows[0].Cells["BarCode"].Value.ToString();
                    this.Close();
                }
            }
        }


________________________________________________

或者这样也行,创建——Windows控件库,自己创建一个重写后的 dataGridView 控件。
然后再工具箱——选择项,功能添加进来,就能“一劳永逸”了。 

转载于:https://www.cnblogs.com/wowait2/archive/2011/07/15/2107707.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值