Custome DataGridView with Row Number and Alternate Row Color


class InfynetDgv : DataGridView
 {
 protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
 {
 this.SuspendLayout();
 base.OnRowPostPaint(e);

// get the row number in leading zero format,
 // where the width of the number = the width of the maximum number
 int RowNumWidth = this.RowCount.ToString().Length;
 StringBuilder RowNumber = new StringBuilder(RowNumWidth);
 RowNumber.Append(e.RowIndex + 1);
 while (RowNumber.Length < RowNumWidth)
 RowNumber.Insert(0, "0");
 // get the size of the row number string
 SizeF Sz = e.Graphics.MeasureString(RowNumber.ToString(), this.Font);
 // adjust the width of the column that contains the row header cells
 if (this.RowHeadersWidth < (int)(Sz.Width + 20))
 this.RowHeadersWidth = (int)(Sz.Width + 20);
 // draw the row number
 e.Graphics.DrawString(
 RowNumber.ToString(),
 this.Font,
 SystemBrushes.ControlText,
 e.RowBounds.Location.X + 15,
 e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2));
 this.ResumeLayout();

}

protected override void OnCellFormatting(DataGridViewCellFormattingEventArgs e)
 {
 this.SuspendLayout();
 base.OnCellFormatting(e);
 var dataGridView = this;

e.CellStyle.Font = new Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular);
 this.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(212, 255, 212);
 if (dataGridView.Rows[e.RowIndex].Selected)
 {
 e.CellStyle.Font = new Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold);
 e.CellStyle.SelectionBackColor = Color.FromArgb(123,123,123);
 }
 DataGridViewCellStyle style = this.ColumnHeadersDefaultCellStyle;

style.BackColor = Color.FromArgb(137,137,137);
 style.ForeColor = Color.White;
 style.Padding= new Padding(3,3,3,3);
 style.Font = new Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold);
 this.ResumeLayout();

}

}
Advertisements

One thought on “Custome DataGridView with Row Number and Alternate Row Color

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s