Search code examples
c#datagridsizescalecells

Fill screen with cells in datagrid depending on size of screen


I have put a datagridview into my windows form. I measure width and height of the screen and then I draw empty cells on the screen. That works fine, problem is that I don't know how much cells I can put on my screen depending on width and height. I get a lot more cells then I should. When I draw them I'am getting more cells than size of my screen on my right and on the bottom of my screen.

I'll put some code so you can see what I am talking about:

public static int height= Screen.PrimaryScreen.Bounds.Height;
public static int width= Screen.PrimaryScreen.Bounds.Width;

public void draw()
{
    number_of_cells_width = width/ 5;  //I have put number 5 because I think they are 5x5 by default size
    number_of_cells_height = height / 5;
    for (int i = 0; i < number_of_cells_width ; i++)
    {
        grid.Columns.Add("", "");
    }
    for (int i = 0; i < number_of_cells_height ; i++)
    {
        grid.Rows.Add("");
    }
}

And I have put datagridview to fill my parent. So I get a lot more cells then I should. Any idea how to fix this?

I think some dividing should do the job. But I don't see what I have done wrong.

Thank you


Solution

  • Screen.PrimaryScreen.Bounds.Width Does not take into account the windows title bars etc ...

    So you will have to take these elements into account if you want to use this method. Or simply get the size of your DataGridView, and calculate from there ?

    DatagridView1.Height and DatagridView1.Width should come in handy.

    Then just put the code in the correct event, so that you reajust when the window gets resized :)

    Edit : the event Resize of the datagridView should suit your needs :)

    Edit 2 :

    foreach (DataGridViewColumn col in DataGridView1.Columns) 
    {
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
        col.Width = 5;
    }
    foreach (DataGridViewRow row in DataGridView1.Rows) 
    {
        row.Height = 5;
    }
    

    The following snippet should parse all columns and rows and set their size to 5. So you will have cells 5*5 and columns which dont autosize