1. 程式人生 > >關於C#WinForm的datagridview控制元件的使用經驗及技巧收集(持續更新)

關於C#WinForm的datagridview控制元件的使用經驗及技巧收集(持續更新)

怎麼讓DataGridView顯示行號?

方法1:

在Winform窗體中選中datagridview控制元件,在其“RowPostPaint”觸發事件屬性中雙擊自動生成事件函式或者在右側的下拉框中選中已寫好的事件函式


選中的事件函式如下(如是雙擊自動生成的,就把函式內的程式碼複製到自動生成的函式內即可):

        private void dgv_ptt_docs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dgv_ptt_docs.RowHeadersWidth - 4,
                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgv_ptt_docs.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dgv_ptt_docs.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

效果如下:


但是據說這種方法每次滾動資料都會觸發RowPostPaint事件,所以在大資料量的時候效能比較差。

方法2:

--------------------------------------------------華麗麗滴分割線-----------------------------------------------

2017-09-15繼續更新

DataGirdView開啟雙緩衝

DataGirdView閃爍非常厲害可以開啟雙緩衝來改善。

以前只知道Form,panel之類的可以使用雙快取,不知道DataGridView也可以使用雙緩衝。當然DataGridView雙緩衝的介面是沒有對外開放的,只能通過反射獲取。
 
      以下是反射獲取雙快取程式碼:
           
 

        public Form()
        {
            //設定窗體的雙緩衝
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();
            
            InitializeComponent();
 
            //利用反射設定DataGridView的雙緩衝
            Type dgvType = this.dataGridView.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
                BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(this.dataGridView, true, null);
        }


      其中this.dataGridView是自己拖的控制元件,name為:dataGridView。設定好以後,閃爍的問題就解決了。