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 控件。
然后再工具箱——选择项,功能添加进来,就能“一劳永逸”了。 

posted @ 2011-07-15 17:59  wowait2  阅读(2890)  评论(0编辑  收藏  举报