简体   繁体   中英

autosize window to fit datagradview vb.net

Is it possible in vb.net to autosize the form window to change it width to the datagridview width?

I have kept looking for a while now but can only find on how to resize the datagridview itself.

This is code for prepare Datagridview

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
   Dim rowvalue As String Dim cellvalue(20) As String 
   Dim streamReader As IO.StreamReader = New IO.StreamReader("test.csv") 

   While streamReader.Peek() <> -1 
     rowValue = streamReader.ReadLine() 
     cellvalue = rowvalue.Split(","c) 
     DataGridView1.Rows.Add(cellValue) 
   End While 

   streamReader.Close() 
 End Sub 

Thanks,

You mean the main form containing the gridview?

Me.Height = heightVal
Me.Width = widthVal

Depending upon the variation in the size of the gridview, you can use the two properties above to adapt the size of the main form. Bear in mind that this will provoke the location of the form to be changed and thus you should also have to affect it at runtime ( Me.Left & Me.Top ).

If it is not the main form, you should replace Me , with the given object (eg, Panel1 ).

----------------- EXAMPLE

    Dim rightGap As Double = 10
    Dim bottomGap As Double = 10
    If (DataGridView1.Location.X + DataGridView1.Width > Me.Width + rightGap) Then
        Me.Width = 2 * Me.Width - (DataGridView1.Location.X + DataGridView1.Width) + rightGap
    End If
    If (DataGridView1.Location.Y + DataGridView1.Height > Me.Height + bottomGap) Then
        Me.Height = 2 * Me.Height - (DataGridView1.Location.Y + DataGridView1.Height) + bottomGap
    End If

I am also including "gaps" both at the right and at the bottom of the form. This code (or something on these lines) should be enough to make sure that the Height/Width values are updated at runtime without any problem (gridview always properly located inside the form). Lastly, you should bear in mind that the size of the datagridview does not have to match the one of columns/rows. In order to avoid wrong resizing, you would have also to make sure that the total width of all the rows matches the width of datagridview and the total height of all the columns its height


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM