阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# DataGridView 小技巧

Posted on 2007-10-09 11:22  宽田  阅读(23604)  评论(0编辑  收藏  举报

1、設置DataGridView的欄位填充整個顯示區
2、調整欄位顯示位置到最後
3、設定控件的欄位自動調整大小
4、設定DataGridView中欄位的寬度
5、得到DataGridView 當前行的位置



設置DataGridView的欄位填充整個顯示區
            //設置DataGridView的欄位填充整個顯示區
            dgvMe.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            
#region
            
/*
             * DataGridViewAutoSizeColumnsMode 定義值來指定要如何調整資料行的寬度。 
             成員名稱             說明 
            AllCells                                     資料行寬度會調整,以適合資料行中的所有儲存格的內容 (包括標題儲存格)。   
            AllCellsExceptHeader                資料行寬度會調整,以適合資料行中的所有儲存格的內容 (不包括標題儲存格)。   
            ColumnHeader                          資料行寬度會調整,以適合資料行行首儲存格的內容。   
            DisplayedCells                           資料行寬度會調整,以適合資料行中的所有儲存格的內容 (位在目前顯示在螢幕上的資料列中),包括標題儲存格。   
            DisplayedCellsExceptHeader      資料行寬度會調整,以適合資料行中的所有儲存格的內容 (位在目前顯示在螢幕上的資料列中),不包括標題儲存格。   
            Fill                                            資料行寬度會調整,使得所有資料行的寬度可以剛好填滿控制項的顯示區,且必須要使用水平捲動方式,才能讓資料行寬度維持在  DataGridViewColumn.MinimumWidth 屬性值之上。相對的資料行寬度是由相對的  DataGridViewColumn.FillWeight 屬性值所決定。  
            None                                        資料行寬度不會自動調整。   

             
*/
            
#endregion

調整欄位顯示位置到最後
                //調整欄位顯示位置到最後
                
//dgvGroupAttr為DataGridView控件
                dgvGroupAttr.Columns[3].DisplayIndex = 5;

設定控件的欄位自動調整大小
                    //設定控件的欄位自動調整大小
                    
//col:DataGridView控件
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

設定DataGridView中欄位的寬度
            //設定DataGridView中欄位的寬度
           dgvEntityHardware.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
           dgvEntityHardware.Columns[
0].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
           dgvEntityHardware.Columns[
0].Width = 110;

成員說明            

AllCells 資料行寬度會調整,以適合資料行中的所有儲存格的內容 (包括標題儲存格)。  

AllCellsExceptHeader 資料行寬度會調整,以適合資料行中的所有儲存格的內容 (不包括標題儲存格)。  

ColumnHeader 資料行寬度會調整,以適合資料行行首儲存格的內容。  

DisplayedCells 資料行寬度會調整,以適合資料行中的所有儲存格的內容 (位在目前顯示在螢幕上的資料列中),包括標題儲存格。  

DisplayedCellsExceptHeader 資料行寬度會調整,以適合資料行中的所有儲存格的內容 (位在目前顯示在螢幕上的資料列中),不包括標題儲存格。  

Fill 資料行寬度會調整,使得所有資料行的寬度可以剛好填滿控制項的顯示區,且必須要使用水平捲動方式,才能讓資料行寬度維持在DataGridViewColumn.MinimumWidth  屬性值之上。相對的資料行寬度是由相對的  DataGridViewColumn.FillWeight 屬性值所決定。 

None 資料行寬度不會自動調整。 

NotSet 資料行的調整大小行為是繼承自 DataGridView.AutoSizeColumnsMode 屬性。 

得到DataGridView 當前行的位置

            //dgvEtList是DataGridView控件
            
//得到DataGridView 當前行的位置
            dgvEtList.CurrentRow.Index