C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C# Source Code


You're Browsing As A Guest! Register Now...
Become a C# Expert!

Join 358,767 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 3,805 people online right now.Registration is fast and FREE... Join Now!




Automatically equalise datagrid columns

This is one method to resize datagrid columns so that they are all of equal size, and fill up the entire client area of the DataGridView

Submitted By: Nayana
Actions:
Rating:
Views: 4,361

Language: C#

Last Modified: January 20, 2008
Instructions: This function assumes that we have are using the System.Windows.Forms name space.

Just paste into the form of choice, or change it to public and put it somewhere else.

To make use of it, call it from the SizeChanged event on the DataGridView, and whenever changes are made to the number or visibility of columns.

e.g.
private void dgvTest_SizeChanged(object sender, EventArgs e) {
EqualizeColumns(dgvTest);
}

And the columns will be resized whenever the DataGridView is resized. E.g. if it is docked, or anchored to opposite sides, it will resize when it's owner Control is resized.

Snippet


  1.     private void EqualizeColumns(DataGridView dgv) {
  2.       int n = dgv.Columns.Count; // Number of columns
  3.  
  4.       // Reduce n to number of VISIBLE columns
  5.       for(int i = 0; i < dgv.Columns.Count; i++)
  6.         if(!dgv.Columns[i].Visible) n--;
  7.  
  8.       /* Resize columns, taking into account the size of the row header, the client area of the
  9.        * DataGridView and the size of the scroll bar. I don't know how to check whether or not
  10.        * the scroll bar is currently visible. */
  11.       for(int i = 1; i < dgv.Columns.Count; i++)
  12.         dgv.Columns[i].Width = dgv.Columns[i].Visible
  13.           ? (dgv.ClientSize.Width - (dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0)
  14.             - SystemInformation.VerticalScrollBarWidth - 2) / n
  15.           : 0; /* set invisible columns to 0, so if they are set to visible, they won't be shown unless
  16.                 * they are explicitly resized. */
  17.     }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month