以编程方式在其他列之间的DataGridview中创建列

时间:2014-10-20 03:49:43

标签: c# datagridview multiple-columns

所以这就是问题,在对StackOverFlow进行一些搜索后,我发现下面只是以编程方式添加列。

   private void AddColumnsProgrammatically()
{
    // I created these columns at function scope but if you want to access 
    // easily from other parts of your class, just move them to class scope.
    // E.g. Declare them outside of the function...
    var col3 = new DataGridViewTextBoxColumn();
    var col4 = new DataGridViewCheckBoxColumn();

    col3.HeaderText = "Column3";
    col3.Name = "Column3";

    col4.HeaderText = "Column4";
    col4.Name = "Column4";

    dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
}

现在我创建列没有问题,但是我想要的是在中间添加这些新列,比如第1列和第2列,所以第2列将转移到第4列,2列新列将是第2列和第3栏。

有人可以给我任何建议或指示吗?

1 个答案:

答案 0 :(得分:0)

您正在寻找DataGridView.Columns.Insert方法在特定索引处插入列:

private void AddColumnsProgrammatically()
{
    // I created these columns at function scope but if you want to access 
    // easily from other parts of your class, just move them to class scope.
    // E.g. Declare them outside of the function...
    var col3 = new DataGridViewTextBoxColumn();
    var col4 = new DataGridViewCheckBoxColumn();

    col3.HeaderText = "Column3";
    col3.Name = "Column3";

    col4.HeaderText = "Column4";
    col4.Name = "Column4";

    // dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    dataGridView1.Columns.Insert(1, col3);
    dataGridView1.Columns.Insert(2, col4);

}