实现现有控件的C#自定义控件
问题描述:
我已经构建了一个从datagridview继承的自定义控件。我需要添加几个其他控件(几个文本框,按钮等),但是因为我从datagridview继承它占用整个矩形(绘制区域)。 我一直在寻找一个例子或方法来做到以下几点: 绘制datagridview(自定义控件),但也在它下面画几个按钮。实现现有控件的C#自定义控件
我觉得我需要从默认的窗体控件继承,然后在其中的一部分绘制datagridview,并在另一部分上绘制按钮。然而在我的搜索中,我还没有找到办法做到这一点。也许我在寻找错误的问题,或者是以错误的方式看待问题。我如何创建一个自定义控件,并在其上绘制了多个现有控件?
答
您可以从TableLayoutPanel继承并在一个单元格中添加自定义的DataGridView控件,并在其他单元格中添加其他必需的控件。
这将允许你使用这个类作为一个包罗万象的控件,内置DataGridView控件和其中包含的所需按钮。
例如:
// Using Statements.
namespace MyNameSpace
{
public class MyControl : TableLayoutPanel
{
// Declare instances of the controls you need.
CustomDataGridView myDataGridControl;
Button button1;
Button button2;
// etc...
public MyControl()
{
// Define TableLayoutPanel properties here,
// e.g. columns, rows, sizing...
myDataGridControl = new CustomDataGridView();
// Define your custom DataGridView here.
button1 = new Button();
// First button properties.
button2 = new Button();
// Second button properties.
// Assign these controls to TableLayoutPanel
// in the specified cells.
Controls.Add(myDataGridControl, 0, 0);
Controls.Add(button1, 0, 1);
Controls.Add(button2, 1, 1);
}
// Methods etc...
}
}
听起来像一个用户控件你是什么 – Plutonix
后呀。谢谢你做了一些搜索,似乎是正确的。感谢您指点我正确的方向。 – lesyriad
正如plutonix所说,你不想从网格继承,你想创建一个UserControl并添加一个网格和所有你需要的控件。 – Gusman