我们可以在TableLayoutPanel中显示多个DataGridView吗?如果是,我们如何实现这一目标?我在msdn上搜索并搜索了它,但无法找到符合我要求的任何内容。
我可以动态多次显示标签,但我正在动态地查找DataGridView。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
尝试以下
public partial class Form1 : Form
{
const int WIDTH = 1200;
const int HEIGHT = 1200;
const int MARGIN = 200;
const int NUMBER_OF_ROWS = 2;
const int NUMBER_OF_COLS = 2;
static List<DataGridView> dgvs = new List<DataGridView>();
public Form1()
{
InitializeComponent();
this.Width = WIDTH;
this.Height = HEIGHT;
TableLayoutPanel panel = new TableLayoutPanel();
this.Controls.Add(panel);
panel.Height = HEIGHT - MARGIN;
panel.Width = WIDTH - MARGIN;
panel.ColumnCount = NUMBER_OF_COLS;
panel.RowCount = NUMBER_OF_ROWS;
for (int row = 0; row < NUMBER_OF_ROWS; row++)
{
for (int col = 0; col < NUMBER_OF_COLS; col++)
{
DataGridView newDGV = new DataGridView();
dgvs.Add(newDGV);
newDGV.Height = (HEIGHT - MARGIN) / NUMBER_OF_ROWS;
newDGV.Width = (WIDTH - MARGIN) / NUMBER_OF_COLS;
newDGV.Left = 50;
newDGV.Top = 50;
panel.Controls.Add(newDGV, col, row);
}
}
}
答案 1 :(得分:1)
目前尚不清楚如何显示子控件。您提到可以使用Label
执行此操作,但是您没有显示任何代码,这有助于澄清。对于DataGridView
,它完全相同。
正如您已经注意到,您只能将一个控件放在TableLayoutPanel
&#34;单元格&#34;中。如果您想要单元格中的多个控件,可以先向Panel
添加TableLayoutPanel
,然后将多个子控件添加到Panel
。
但是,我认为您真正想要的是TableLayoutPanel
中可变数量的列或行,然后每个单元格添加一个DataGridView
。
首先,创建TableLayoutPanel
或获取现有实例。
// If you are using an existing table layout panel, either clear the controls, rows and columns beforehand,
// or keep track of them manually and adjust accordingly.
tableLayoutPanel.Controls.Clear();
tableLayoutPanel.RowStyles.Clear();
tableLayoutPanel.ColumnStyles.Clear();
IList<DataGridView> dataGridViews = ... /* wherever you get your data grid views from */
for (int i = 0; i < dataGridViews.Count; ++i)
{
// The arguments to ColumnStyle control the size of the column.
// If you want to arrange them vertically instead of horizontally, use RowStyles instead.
// If you want a combination, you have to figure out the logic yourself.
// In case of SizeType.Percent, "width" defines a relative weight, not necessarily percent.
// If all widths are equal (no matter the value), all columns will be equally wide.
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, width: 1));
dataGridViews[i].Dock = DockStyle.Fill;
// This adds the data grid view into that specific cell.
tableLayoutPanel.Controls.Add(dataGridViews[i], column: i, row: 0);
}