我现在一个界面有两个完全相同的DataGridView,字段什么的都一样,现在我希望在第一个DataGridView写的事件,在第二个DataGridView上面也能应用,(都是一些限制输入的验证功能事件)比如说:private void dgvInfo_KeyPress(object sender, KeyPressEventArgs e)
        {
            //dgvInfo是第一个DataGridView的名字,我现在希望将这里面的dgvInfo能用一个通用的名字代替,这样我两个DataGridView都可以调用这个事件调用            if (dgvInfo.Rows.Count <= 0) return;
            int columnIndex = dgvInfo.CurrentCell.ColumnIndex;
            int rowIndex = dgvInfo.CurrentCell.RowIndex;            if (columnIndex == 2 || columnIndex==5)//配额重量和失效时间只能输入数字
            {
                if (!PublicControlUtility.InputOnlyNumber(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
            if (columnIndex == 1)//配额品名只能输入数字和“/”
            {
                if (!PublicControlUtility.InputOnlyLetterAndIntegerAndSpeChar(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
        }
不知道大家有没有明白??

解决方案 »

  1.   

    不用改名字,将第二个DataGridView的KeyPress事件也设成这个就行了
      

  2.   

    把两个控件的KeyPress事件都指向你写的这个DataGridView dgv = (DataGridView)sender;//在事件中开始添加这句,dgv 就是触发事件的DataGridView 。
      

  3.   

    这个不好办吧,一个dataGridview只对自己的有效.注册时也只是自己的
    除非你把这些事件封装一下,然后每个dataGridView的KeyPress都调用一下,那要可行
      

  4.   

    这种方法对别的事件是可以的,但是对KeyPree来说就会报错:无法将类型为“System.Windows.Forms.DataGridViewTextBoxEditingControl”的对象强制转换为类型“System.Windows.Forms.DataGridView”。帮我看看还有没有别的办法
      

  5.   

    这个是可以
    别的4楼的
    DataGridView dgv = (DataGridView)sender;//在事件中开始添加这句,dgv 就是触发事件的DataGridView 。好像也是行的
      

  6.   

    dataGridView1.KeyPress += new KeyPressEventHandler(dgvInfo_KeyPress);
    dataGridView2.KeyPress += new KeyPressEventHandler(dgvInfo_KeyPress);private void dgvInfo_KeyPress(object sender, KeyPressEventArgs e)
            {
                DataGridView dgv = sender as DataGridView;
                //....
            }