我想在tablelayout中动态分配datagridview。
例如,我选择网格数,(2,4,9,16 ......)
接下来,创建这个数量的datagridview控件并将它们放在tablelayout中。
示例:
那么,如何使用一个tablelayout
动态分配一些Datagridview答案 0 :(得分:0)
我创建了新表单(Form1
),添加了名为TableLayoutPanel
的新t
,并为表单构造函数添加了此代码:
public Form1()
{
InitializeComponent();
int row = 1; // number of rows
int col = 2; // number of columns (change them to see effect)
var grids = new DataGridView[row,col];
// create rows and set their height
t.RowCount = row;
t.RowStyles.Clear();
for (int r = 0; r < row; r++)
{
var style = new RowStyle();
style.SizeType = SizeType.Percent;
style.Height =(float)(1.0/row);
t.RowStyles.Add(style);
}
// create columns and set their width
t.ColumnCount = col;
t.ColumnStyles.Clear();
for (int c = 0; c < col; c++)
{
var style = new ColumnStyle();
style.SizeType = SizeType.Percent;
style.Width = (float)(1.0 / col);
t.ColumnStyles.Add(style);
}
// dynamically add grid in necessary place in layout
for(int r = 0; r<row; r++)
for (int c = 0; c < col; c++)
{
grids[r,c] = new DataGridView()
{
Dock = DockStyle.Fill,
};
t.Controls.Add(grids[r, c], c, r);
}
}