Winform中的dataGridView添加自動編號
阿新 • • 發佈:2018-05-19
項目 style for send 顯示 datagrid renderer 顯示數據 再次
新建一個WinForm項目,在工具欄裏拖一個dataGriView到窗體中,默認名稱為dataGridView1,把數據源添加到dataGridView1中,運行,看到dataGriView1有數據顯示,但沒有行編號,所以我們需要添加一列,用來顯示行號,以便我們知道這是第幾條記錄。選中dataGriView1,然後在屬性列表的事件選擇RowPostPaint事件,雙擊後添加事件處理函數,代碼如下:
privatevoid dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { //自動編號,與數據無關 Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dataGridView1.RowHeadersWidth - 4, e.RowBounds.Height); TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); }
再次運行程序,就能看到多了一個標題列,顯示數據的行號!!嘻嘻。。。
Winform中的dataGridView添加自動編號