开发者

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

开发者 https://www.devze.com 2023-02-25 04:05 出处:网络
I have a mydatagridview class which inherits from the built-in DataGridView control, as shown below: public class mydatagridview : DataGridView

I have a mydatagridview class which inherits from the built-in DataGridView control, as shown below:

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 Ut开发者_如何学运维ilize myDatagridview with Datagridview1 of : public partial class 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. 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. It will automatically insert code very similar to that shown above inside the InitializeComponent() method.

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:

  1. From the "Tools" menu, select "Options".

  2. Expand the "Windows Forms Designer" category.

  3. Set the "AutoToolboxPopulate" property to True.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号