我希望我的表格大小适合数据网格视图。数据网格视图大小始终相同,但表可以更改行数和列数。
以下是我填充表格的方法:
public DataTable createGridForForm(int rows, int columns)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= columns; i++)
{
table.Columns.Add("column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
ListBox test = new ListBox();
myTabPage.Controls.Add(test);
table.Rows.Add(dr);
}
return table;
}
以下是我创建datagridview的方法:
private void createGridInForm(int rows, int columns)
{
DataGridView RunTimeCreatedDataGridView = new DataGridView();
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
//DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
//ID_Column.Width = 200;
int positionForTable = getLocationForTable();
RunTimeCreatedDataGridView.BackgroundColor = Color.WhiteSmoke;
RunTimeCreatedDataGridView.Size = new Size(995, 200);
RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
}
尝试此代码时出错:
//DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
//ID_Column.Width = 200;
错误说:
指数超出范围。它可能不是负数,必须小于
答案 0 :(得分:0)
如果在获取Columns[0]
之前将数据网格添加到选项卡控件,则不会出现该错误。
你的代码应该是这样的:
DataGridView RunTimeCreatedDataGridView = new DataGridView();
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
ID_Column.Width = 200;
修改强>
我添加了详细的行,以便将DataGridView
填充到它的容器中。
private void createGridInForm(int rows, int columns)
{
DataGridView RunTimeCreatedDataGridView = new DataGridView();
RunTimeCreatedDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
// fill the gridview to its container
DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
ID_Column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
RunTimeCreatedDataGridView.Dock = DockStyle.Fill;
}
答案 1 :(得分:0)
以下行可用于使用数据网格视图中的特定列填充额外空间
RunTimeCreatedDataGridView .Columns["column_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
如果将所有列的此属性设置为 DataGridViewAutoSizeColumnMode.Fill ,则所有列都采用相同的宽度
答案 2 :(得分:0)
这就是它
表示宽度 -
RunTimeCreatedDataGridView.AutoSizeColumnsMode=System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
和高度 -
totalRowHeight = RunTimeCreatedDataGridView.ColumnHeadersHeight;
foreach (DataGridViewRow row in RunTimeCreatedDataGridView.Rows)
totalRowHeight += row.Height;