我正在vb.net的组框内创建一个文本框网格。它们都是统一的宽度,高度,字体等。我现在的代码就是这样:
Dim new_cell As New TextBox
With new_cell
.Multiline = True
.Width = cell_width
.Height = cell_height
.Font = ("arial", 12)
End With
For j = 0 To N
For i = 0 To M
new_cell.Left = (i * cell_width) + i
new_cell.Top = (j * cell_width) + j
space.Controls.Add(new_cell)
Next
Next
其中M,N是网格大小,空间是组框。 这应该创建整个网格,但它只在底角创建一个文本框。这是因为在循环的下一次迭代中对new_cell的更改会影响先前的控件,因此永远不会添加新控件。我可以用一个数组替换单个文本框,然后循环并将文本框数组的每个元素添加到组框中。然而,这会产生丑陋的代码并且看起来效率低下(每个单元格的重复属性),所以我想知道是否有办法将控件添加到组框,然后取消关联(或者某些)文本框变量和添加到的文本框组合框。
答案 0 :(得分:2)
您只创建一个 TextBox
。您需要在Dim new_cell As New TextBox
循环中移动i
。
For j = 0 To N
For i = 0 To M
Dim new_cell As New TextBox
With new_cell
.Multiline = True
.Width = cell_width
.Height = cell_height
.Font = ("arial", 12)
End With
new_cell.Left = (i * cell_width) + i
new_cell.Top = (j * cell_width) + j
space.Controls.Add(new_cell)
Next
Next
甚至更好:
Dim cell_x As Integer = space.DisplayRectangle.Left
Dim cell_y As Integer = space.DisplayRectangle.Top
Dim cell_i As Integer = 0 ': Cell `i` spacing
Dim cell_j As Integer = 0 ': Cell `j` spacing
For j = 0 To N
For i = 0 To M
space.Controls.Add(New TextBox() With {
.Name = String.Format("N{0}M{1}", j, i),
.Multiline = True,
.Width = cell_width,
.Height = cell_height,
.Font = New Font("arial", 12),
.Left = (cell_x + (i * (cell_width + cell_i))),
.Top = (cell_y + (j * (cell_height + cell_j)))
})
Next
Next