繁体   English   中英

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

[英]How can I use a custom control class that inherits from a built-in control on my main form?

我有一个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()方法中插入与上面显示的代码非常相似的代码。

如果重建项目后自定义控件未自动显示在工具箱中,请确保已启用工具箱自动填充

  1. 从“工具”菜单中,选择“选项”。
  2. 展开“ Windows窗体设计器”类别。
  3. 将“ AutoToolboxPopulate”属性设置为True。

    在VS选项中将AutoToolboxPopulate设置为True

如果我理解正确,但不确定是否可以这样做,则可以像使用任何其他类型一样使用它:

mydatagridview mydatagrid = new mydatagridview();
this.Controls.Add(mydatagrid);

在已经给出的答案旁边,应该可以将控件从工具箱拖放到表单中。

如果您创建用户控件或自定义控件,并生成您的项目,则该控件应显示在工具箱中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM