在Visual Basic中动态添加面板和单选按钮

时间:2011-12-01 18:38:09

标签: vb.net radio-button panel

伙计们我试图动态创建每个都有七个单选按钮的面板。 我得到了面板,但每个面板上只有1个单选按钮。我在这做错了什么? QuestionQuantity是一个整数,是决定我将创建多少个面板的变量。代码位于表单加载函数中。

谢谢,

Dim Pan As Panel
Dim RButton As RadioButton

For x As Integer = 1 To QuestionsQuantity Step 1
        Pan = New Panel
        Pan.Name = "Panel" & Convert.ToString(x)
        Pan.Left = 300
        Pan.Top = 100 + 52 * (x - 1)
        Pan.Height = 48
        Pan.Width = 280
        Pan.BackColor = Color.Coral
        Controls.Add(Pan)

        For y As Integer = 1 To 7 Step 1
            RButton = New RadioButton
            RButton.Name = "RadioButton" & Convert.ToString(x) & Convert.ToString(y)
            RButton.Left = 1 + 30 * (y - 1)
            RButton.Top = 10
            RButton.Text = Convert.ToString(y)
            RButton.CheckAlign = System.Drawing.ContentAlignment.BottomCenter
            RButton.TextAlign = System.Drawing.ContentAlignment.TopCenter
            RButton.UseVisualStyleBackColor = True
            Controls.Add(RButton)
            Pan.Controls.Add(RButton)
        Next
Next

我弄乱了它并取出了Panel部分并且只是使用了RadioButtons以查看我是否得到了其中的七个。如果我在y方向(.top)上设置它们,我可以得到7但是在x(.left)方向上由于某种原因它不起作用

For y As Integer = 1 To 7 Step 1
    RButton = New RadioButton
    RButton.Name = "RadioButton1" & Convert.ToString(y)
    RButton.Left = 20 + (y * 30)
    RButton.Top = 10
    RButton.Text = Convert.ToString(y)
    RButton.CheckAlign = System.Drawing.ContentAlignment.BottomCenter
    RButton.TextAlign = System.Drawing.ContentAlignment.TopCenter
    RButton.UseVisualStyleBackColor = True
    Controls.Add(RButton)
Next

请帮助我!

我终于明白了。问题是声明RadioButton的大小。即使我把间距做得更大,如果不宣布它也会太大。

RButton.Size = New System.Drawing.Size(17, 30)

解决了这个问题。

3 个答案:

答案 0 :(得分:1)

您应该使用包含七个单选按钮的UserControl。

For x As Integer = 1 To QuestionsQuantity
  Dim pan As New QuestionUserControl
  Pan.Name = "Panel" & Convert.ToString(x)
  Pan.Left = 300
  Pan.Top = 100 + 52 * (x - 1)
  Pan.Height = 48
  Pan.Width = 280
  Pan.BackColor = Color.Coral
  Me.Controls.Add(Pan)
Next

如果坚持使用当前代码,请将其删除(您应该只将其添加到面板中):

For y As Integer = 1 To 7
  '// Controls.Add(RButton)
  Pan.Controls.Add(RButton)
Next

就看控制而言,我猜你不够“正确”:

Dim leftMark As Integer = 20
For y As Integer = 1 To 7
  '// code
  RButton.Left = leftMark
  '//code

  leftMark += rButton.Width + 4
Next

答案 1 :(得分:0)

  1. 有一个Pan.Height = 48,里面的控件不会太多。
  2. 您是否将按钮添加到面板和控件?

答案 2 :(得分:0)

将radiobuttons放入网格框中。您可以根据需要动态添加radiobuttons行。如果这对您有用,我回家后会发送示例代码。