我在自动排序datagridview时遇到问题。 当我单击列标题一次时,它的值被排序但三角标记保持不变,因此它指向错误的方向。 在第二次单击时,它是更改的三角形(现在将指向不同的方向,但在将其与datagridview中的值进行比较时更正) 然后,排序过程重复 - 所以如果我想对列进行排序,我必须单击标题两次:首先更改方向标记/字形,然后再排序值。
我认为这不重要,但对于这个DGV,我使用BindingList作为数据源。
设计师代码:
//
// dgv
//
this.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgv.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] {
this.monthColumn,
this.colorColumn} );
this.dgv.Location = new System.Drawing.Point( 22, 127 );
this.dgv.Name = "dgv";
this.dgv.Size = new System.Drawing.Size( 468, 164 );
this.dgv.TabIndex = 0;
this.dgv.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler( this.dgv_CellBeginEdit );
this.dgv.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dgv_CellClick );
this.dgv.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler( this.dgv_CellEndEdit );
this.dgv.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler( this.dgv_RowsAdded );
//
// monthColumn
//
this.monthColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.monthColumn.DefaultCellStyle = dataGridViewCellStyle3;
this.monthColumn.HeaderText = "Miesiące";
this.monthColumn.Name = "monthColumn";
this.colorColumn.ValueType = typeof( int );
this.monthColumn.Width = 72;
//
// colorColumn
//
this.colorColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.colorColumn.DefaultCellStyle = dataGridViewCellStyle4;
this.colorColumn.HeaderText = "Barwa";
this.colorColumn.Name = "colorColumn";
this.colorColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.colorColumn.ValueType = typeof( System.Drawing.Color );
绑定程序:
dgv.AutoGenerateColumns = false;
monthColumn.DataPropertyName = "Months";
colorColumn.DataPropertyName = "Color";
colorColumn.ReadOnly = false;
dgv.DataSource = bcolors;//BindingList
dgv.Sort( monthColumn, ListSortDirection.Ascending );
事件方法用于将backgroundcolor应用于行并禁止编辑colorColumn(readonly不起作用?,但这不是重点)
答案 0 :(得分:0)
您可以尝试更改列的sortmode吗?
改变这个:
this.colorColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
进入这个:
this.colorColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;