C# dataGridView空白列的設置

隱藏空白列:

dataGridView1.RowHeadersVisible = false;

設置空白列的寬度不可改變:

 this.dgv.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;

在空白列顯示行數的方法:

       private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //#region 方法一
            //using (SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor))
            //{
            //    int linen = 0;
            //    linen = e.RowIndex + 1;
            //    string line = linen.ToString();
            //    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
            //    SolidBrush B = new SolidBrush(Color.Red);
            //}
            //#endregion
            #region 方法二
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(
                e.Graphics, (e.RowIndex + 1).ToString(),
                dgv.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dgv.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter
                );
            #endregion
        }

如果你是使用Table綁定的Gridview建議使得如下方法:

  //實現功能  DataGridView  添加 自動編號   
            DataTable table =new DataTable();


            DataColumn column = new DataColumn();
            column.AutoIncrement = true;    //AutoIncrement  獲取或設置一個值,該值指示對於添加到該表中的新行,列是否將列的值自動遞增  
            column.ColumnName = "自動編號";
            column.AutoIncrementSeed = 1;
            column.AutoIncrementStep = 1;
            table.Columns.Add(column);
            table.Merge(table);//Merge合併DataTable  
            this.dataGridView1.DataSource = table;  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章