有人認爲,當DataGridView1的寬度和高度分別與寬度和形狀的高度,寬度和高度相比如果它們超出了窗體的尺寸,則重置它們,滾動條變得可見。
嘗試下面的代碼,這將動態DataGridView控件添加到窗體,並創建一個正方形格子的行和列標題名稱:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Following code adds a Datagridview control to a Form dynamically
'Step 1. Add a textbox to a Form, and input the number of columns (ncol). (Note: in this example, ncol=nrow).
'Step 2. Set the Form's Windowstate property to Maximized
For Each cont As Control In Me.Controls 'remove DataGridView if it already exists on the Form
If TypeOf (cont) Is DataGridView Then
Me.Controls.Remove(cont)
End If
Next
Dim DataGridView1 As New DataGridView 'create new data grid view dynamically during run-time
Me.Controls.Add(DataGridView1) 'add the data grid view to the Form
Me.Refresh()
Dim i, nrow, ncol As Integer ' ncol=nrow -->this is a square grid
ncol = TextBox1.Text
nrow = ncol 'Note: add a second textbox to the form and input nrow if you don't want a square grid
DataGridView1.Visible = True
DataGridView1.Top = 100
DataGridView1.Left = 100
DataGridView1.Rows.Clear()
Do While DataGridView1.Columns.Count > 0
DataGridView1.Columns.RemoveAt(DataGridView1.Columns.Count - 1)
Loop
For i = 1 To ncol
DataGridView1.Columns.Add(i, "V" & i)
Next
DataGridView1.Width = ncol * 115
DataGridView1.Height = nrow * 22 + 45
If DataGridView1.Width > Me.Width - DataGridView1.Left Then DataGridView1.Width = Me.Width - DataGridView1.Left - 20
If DataGridView1.Height > Me.Height - DataGridView1.Top Then DataGridView1.Height = Me.Height - DataGridView1.Top - 50
DataGridView1.ScrollBars = ScrollBars.None
For i = 1 To nrow
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(i - 1).HeaderCell.Value = "V" & i
Next
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
DataGridView1.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle
DataGridView1.AllowUserToAddRows = False
DataGridView1.ScrollBars = ScrollBars.Both
Me.WindowState = FormWindowState.Maximized
End Sub
仍然是一個雜牌,但稍微好一點。謝謝。 :) – ReturningTarzan 2012-02-05 00:01:10
超級!保存我))) – Konstantin 2015-12-22 18:01:07
這個工作得很好,但是'SetDataSource'也可以調用'PerformLayout()'! – 2017-01-19 08:53:49