我想简化这段代码:
DataGridViewColumn column1 = dataGridView1.Columns[0];
column1.Width = 300;
DataGridViewColumn column2 = dataGridView2.Columns[0];
column2.Width = 300;
将信息放入foreach循环。我试过这个:
foreach (DataGridView dgv in this.Controls.OfType<DataGridView>())
{
DataGridViewColumn column = dgv.Columns[0];
column.Width = 300;
}
我没有工作 - 你知道问题出在哪里吗?
答案 0 :(得分:1)
您应该遍历DataGridView的Columns集合
foreach (DataGridViewColumn column in dataGridView1.Columns)
column.Width = 300;
如果你只需要在前两列上循环,那么
foreach (DataGridViewColumn column in dataGridView1.Columns
.Cast<DataGridViewColumn>()
.Take(2))
column.Width = 300;
或表单中的所有DataGridViews
foreach(DataGridView dgv in this.Controls.OfType<DataGridView>())
foreach (DataGridViewColumn column in dgv.Columns)
column.Width = 300;