Hi :)

I have some questions:

1) How can i get the size of the screen ? (not the forum, the
screen borders)
2) How can i resize all the columns in a DataGridView
to the length of their values ? (when using the built in
method, Autoresize, its only make it larger but dont make
it small if the value is shorter then the column)
3) How can i check if a specific KeyBoard key pressed ? (like Up or A buttons)
4) How can i change a specific Column Behavior in a DataGridView ? (like i want that
only the fields of this Column will be limited to 4 digits)

Thanks.

1) How can i get the size of the screen ? (not the forum, the
screen borders)

You can find that stuff in the SystemInformation class.

2) How can i resize all the columns in a DataGridView
to the length of their values ?

The only sure way I know is to find the longest column value for each column in all of the rows and fit the column width to it. I haven't done it with a DataGridView, but this is what I use for a DataGrid. Maybe it'll help you write your own.

public static void AutoSizeColumns( DataGrid grid ) {
  System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd( grid.Handle );
  GridColumnStylesCollection cs = grid.TableStyles[0].GridColumnStyles;
  object ds = grid.DataSource;

  for ( int style = 0; style < cs.Count; style++ ) {
    int rowCount = ( ds is DataView ) ? ( ds as DataView ).Count : ( ds as DataTable ).Rows.Count;
    string format = "{0}";

    if ( cs[style] is DataGridTextBoxColumn ) {
      format = "{0:" + ( cs[style] as DataGridTextBoxColumn ).Format + "}";
    }

    // The default minimum width is the header text
    System.Drawing.SizeF maxWidth = g.MeasureString( cs[style].HeaderText, grid.Font );

    // Find the widest row in the grid for this column
    for ( int i = 0; i < rowCount; i++ ) {
      System.Drawing.SizeF cellWidth = g.MeasureString( string.Format( format, grid[i, style] ), grid.Font );

      if ( cellWidth.Width > maxWidth.Width ) {
        maxWidth = cellWidth;
      }
    }

    cs[style].Width = (int)maxWidth.Width + 8;
  }

  g.Dispose();
}

3) How can i check if a specific KeyBoard key pressed ? (like Up or A buttons)

Anything that derives from the Control class has a KeyDown event with event arguments that tell you what key was pressed.

4) How can i change a specific Column Behavior in a DataGridView ?

If you can't fiddle with the properties, you have to handle events and do it manually. I think the last time I did numeric input in a DataGridView text box column, I handled the KeyDown event and suppressed the keypress if the key value wasn't a digit. And you can set a property that limits the number of characters that the column allows.

This article has been dead for over six months. Start a new discussion instead.