自动动态添加控件
我有一个数据库有若干条记录(<100条),我希望将数据读取出来,按实际的数据条目数添加Label,能实现动态自动的增减,并很均匀分布在Form上。 最好所有label可以跟form大小变化大小。我的目的是可以实现目视化显示数据基本效果如同编写计算器自动生成按钮一样,我不太会实现换行和自动分布!请大家指点
[此贴子已经被作者于2016-7-7 16:52编辑过]
[此贴子已经被作者于2016-7-6 17:01编辑过]
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim i As Integer Dim nTop As Long = 0, nLeft As Long = 0 Dim Label(0 To 9) As Label For i = 0 To 9 Label(i) = New Label Controls.Add(Label(i)) With Label(i) .Left += nLeft .Height = 30 .Top = nTop .BorderStyle = BorderStyle.FixedSingle .Visible = True .Text = "Label" & i nLeft += .Width + 10 If nLeft + .Width >= Me.Width Then nLeft = 0 nTop = nTop + 30 * 2 End If End With Next i End Sub
[此贴子已经被作者于2016-7-8 17:00编辑过]
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.WindowState = FormWindowState.Maximized Dim i As Integer, num As Integer Dim nTop As Long = 0, nLeft As Long = 0 100: Try num = InputBox("请输入要加载的Lable数量") Catch ex As Exception MsgBox("请输入一个合法的整数") GoTo 100 End Try Dim Label(0 To num - 1) As Label For i = 0 To num - 1 Label(i) = New Label Controls.Add(Label(i)) With Label(i) .Left += nLeft .Height = 30'将标签的高度设为30 .Top = nTop .BorderStyle = BorderStyle.FixedSingle .TextAlign = ContentAlignment.MiddleCenter '设置文字居中对齐 .Visible = True .Text = "Label" & i nLeft += .Width + 10'将标签的左右间距设为10 If nLeft + .Width >= Me.Width Then '如果下一个Label将超出窗体的宽度,换行显示 nLeft = 0 nTop = nTop + .Height +15'将标签的行间距设为15 End If End With Next i End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.WindowState = FormWindowState.Maximized Dim i, num As Integer Dim nTop As Long = 0, nLeft As Long = 0 100: Try num = InputBox("请输入要加载的Lable数量") Catch ex As Exception MsgBox("请输入一个合法的整数") GoTo 100 End Try Dim Label(0 To num - 1) As Label '根据输入的指定数值定义Label对象 For i = 0 To num - 1 Application.DoEvents()'设置程序友好响应 Label(i) = New Label Controls.Add(Label(i)) With Label(i) .SetBounds(nLeft, nTop, 60, 30) '将标签的高度设为30,宽度设为60 .BorderStyle = BorderStyle.FixedSingle .TextAlign = ContentAlignment.MiddleCenter '设置文字居中对齐 .Text = "Label" & i .Tag = i '这个属性用来识别每个Label对象 .Visible = True AddHandler Label(i).Click, AddressOf LabelClick '将刚创建的标签关联上单击事件 '为即将创建的下一个标签设置坐标 nLeft += .Width + 10 '将标签的左右间距设为10 If nLeft + .Width >= Me.Width Then '如果下一个Label将超出窗体的宽度,换行显示 nLeft = 0 nTop += .Height + 15 '将标签的行间距设为15 End If End With Next i End Sub Private Sub LabelClick(ByVal sender As System.Object, ByVal e As System.EventArgs) '自定义一个过程,用来响应各个标签对象的单击事件 MsgBox("你点击了Label" & sender.Tag) Select Case sender.Tag Case 0 To 20 sender.ForeColor = Color.Blue Case 21 To 40 sender.ForeColor = Color.Red Case Else sender.ForeColor = Color.White End Select sender.Text = "我被点中了" End Sub