如何使用从主窗体上的内置控件继承的自定义控件类?

| 我有一个mydatagridview类,它从内置的
DataGridView
控件继承,如下所示:
public class mydatagridview : DataGridView 
{
    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter) 
        {
            this.ProcessTabKey(e.KeyData);
            return true;
        }
        return base.ProcessDataGridViewKey(e);
    }

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter) 
        {
            this.ProcessTabKey(keyData);
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
}
现在,我想在我的主课中使用它:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
}
我想将myDatagridview与Datagridview1一起使用:公共局部类Form1:Form 我怎样才能做到这一点?     
已邀请:
您需要创建自定义控件类的实例,然后将该实例添加到表单的
Controls
集合中。例如:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Create an instance of your custom control
        mydatagridview myDGV = new mydatagridview();

        // Add that instance to your form\'s Controls collection
        this.Controls.Add(myDGV);
    }
}
当然,您也可以从Designer中执行相同的操作。它会自动在
InitializeComponent()
方法中插入与上面显示的代码非常相似的代码。 如果在重建项目后自定义控件未自动显示在工具箱中,请确保已启用工具箱自动填充: 从\“工具\”菜单中,选择\“选项\”。 展开\“ Windows窗体设计器\”类别。 将\“ AutoToolboxPopulate \”属性设置为True。     
如果我理解正确,但是我不确定我可以这样做,则可以像使用任何其他类型一样使用它:
mydatagridview mydatagrid = new mydatagridview();
this.Controls.Add(mydatagrid);
    
在已经给出的答案旁边,应该可以将控件从工具箱拖放到表单中。 如果您创建用户控件或自定义控件,并生成您的项目,则该控件应显示在工具箱中。     

要回复问题请先登录注册