【问题标题】:How to set DataGridView column properties for automatically generated columns?如何为自动生成的列设置 DataGridView 列属性?
【发布时间】:2009-02-06 16:12:17
【问题描述】:

我在绑定到DataGridViewDataTable 中编辑数据。在DataTable 中创建新列时,视图中会生成一个新列。

通常我会在DataGridView_ColumnAdded 事件中设置视图列属性,但是目前列的默认设置是添加一个视图列,其中SortMode 设置为Automatic,这与DataGridView @ 不兼容987654328@ 属性并在列添加事件可以触发之前导致错误。

我想我可以通过为新生成的列定义一个“模板”列来解决这个问题 - 但是如何?

【问题讨论】:

    标签: c# winforms visual-studio-2008 datagridview


    【解决方案1】:

    好的,是时候破解它了:

    为了演示,这里有一个小应用程序:

     public partial class Form1 : Form
        {
            DataTable table = new DataTable();
            public Form1()
            {
                InitializeComponent();
                this.dataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
                this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);
            }
    
            void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
            {
                Console.WriteLine("Column added");
                e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                table.Columns.Add("Name");
                table.Columns.Add("Age", typeof(int));
    
                table.Rows.Add("John", 27);
                this.FlipSelectionMode();
                this.dataGridView1.DataSource = table;
                this.FlipSelectionMode();
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                this.FlipSelectionMode();
                table.Columns.Add("Height",typeof(int));
                table.Rows[0]["Height"] = 60;
                this.FlipSelectionMode();
            }
    
            private void FlipSelectionMode()
            {
                this.dataGridView1.SelectionMode = this.dataGridView1.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect ? DataGridViewSelectionMode.CellSelect : DataGridViewSelectionMode.ColumnHeaderSelect;
            }
        }
    

    基本上,一开始我将DataGridView的选择模式设置为ColumnHeaderSelect。在 button1 单击时,我将内容添加到数据表中,然后将其绑定到 DataGridView。诀窍是,我在绑定 DGV 之前和之后调用了一个名为 FlipSelectionMode() 的方法。它的作用是,如果它处于 columnheaderselect 模式,它会将其翻转为单元格选择,反之亦然。这样就可以添加列。然后,在添加列事件中,我将列排序属性设置为程序化,否则,您将无法添加另一列。为了证明这一点,在 button2 单击时,它只是添加了另一列,同时在前后翻转选择模式。

    我同意,这完全是 hack,但 DGV 很时髦。我遇到了很多问题,而且我几乎总是不得不修改一些东西。

    【讨论】:

      【解决方案2】:

      有趣 - 我对 DataGridView 做了很多,但我还没有看到这个。也许务实的选择可能是手动构建列?可能不是你想听到的……

      【讨论】:

      • 手动是什么意思 - 在设计器中还是以编程方式?我尽量不使用设计器,因为我反映的数据是用于任意大小的双精度数据集,因此列数变化很大。
      • 以编程方式 - 通过遍历视图列。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2010-12-09
      相关资源
      最近更新 更多