[英]How can I use a custom control class that inherits from a built-in control on my main form?
I have a mydatagridview class which inherits from the built-in DataGridView
control, as shown below: 我有一个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);
}
}
Now I want to utilize it in my main class: 现在,我想在我的主课中使用它:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
I want to Utilize myDatagridview with Datagridview1 of : public partial class Form1 : Form 我想将myDatagridview与Datagridview1一起使用:公共局部类Form1:Form
How can I do this? 我怎样才能做到这一点?
You need to create an instance of your custom control class, and then add that instance to your form's Controls
collection. 您需要创建自定义控件类的实例,然后将该实例添加到窗体的
Controls
集合中。 For example: 例如:
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);
}
}
Of course, you could also do the same thing from the Designer. 当然,您也可以从Designer中执行相同的操作。 It will automatically insert code very similar to that shown above inside the
InitializeComponent()
method. 它将自动在
InitializeComponent()
方法中插入与上面显示的代码非常相似的代码。
If your custom control doesn't show up in the Toolbox automatically after you've rebuilt your project, make sure that you've enabled toolbox auto-population : 如果重建项目后自定义控件未自动显示在工具箱中,请确保已启用工具箱自动填充 :
Set the "AutoToolboxPopulate" property to True. 将“ AutoToolboxPopulate”属性设置为True。
If I understand correctly, and i'm not sure that I do, you can just use it like any other type: 如果我理解正确,但不确定是否可以这样做,则可以像使用任何其他类型一样使用它:
mydatagridview mydatagrid = new mydatagridview();
this.Controls.Add(mydatagrid);
Next to the answers that have already been given, it should be possible to drag and the drop the control from the toolbox to your form. 在已经给出的答案旁边,应该可以将控件从工具箱拖放到表单中。
If you create a user control, or a custom Control, and build your project, the control should show up in the toolbox. 如果您创建用户控件或自定义控件,并生成您的项目,则该控件应显示在工具箱中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.