开发者

vb.net dynamically create checkboxes

I am trying to figure out how to go about creating dynamic checkboxes on my form when I do not know exactly how many b开发者_Go百科oxes I will need.

The problem is that I do not know how to DIM more than one object. This is my code for creating one checkbox

Dim checkBox As New CheckBox()

Form1.Controls.Add(checkBox)
checkBox.Location = New Point(10, 10)
checkBox.Text = "testing"
checkBox.Checked = True
checkBox.Size = New Size(100, 20)

It works just fine but i am unable to add more than one checkBox without having to do this:

Dim checkBox As New CheckBox()
Dim checkBox2 As New CheckBox()

Form1.Controls.Add(checkBox)
checkBox.Location = New Point(10, 10)
checkBox.Text = "testing"
checkBox.Checked = True
checkBox.Size = New Size(100, 20)

Form1.Controls.Add(checkBox2)
checkBox2.Location = New Point(40, 10)
checkBox2.Text = "testing2"
checkBox2.Checked = True
checkBox2.Size = New Size(100, 20)

etc...

Is there a way to dim more than 1 checkbox instead of having to write multiple dim statements for each checkBoxe?

Sorry maybe i should say this..

I'm looking to do something like this:

 dim checkBox() as CheckBox

 do until i = 50
    Form1.Controls.Add(checkBox(i))
    checkBox(i).Location = New Point(10, 10)
    checkBox(i).Text = "testing " & i
    checkBox(i).Checked = True
    checkBox(i).Size = New Size(100, 20)
    i += 1
 loop


It seems like the only items that are different and not calculated between the CheckBox instances is the text. If so then you could just use the following code to add a set of CheckBox instances based off of a list of String's.

Dim data as String() = New String() { "testing", "testing2" }
Dim offset = 10
For Each cur in data 
  Dim checkBox = new CheckBox()
  Form1.Controls.Add(checkBox)
  checkBox.Location = New Point(offset, 10)
  checkBox.Text = cur
  checkBox.Checked = True
  checkBox.Size = New Size(100, 20)
  offset = offset + 30
Next


Put it in a loop, including the new statement but varing the position.

You could also clone the object, maybe with performance penalties ... Sorry but don't know Vb.net, I will give you the c# code hoping it will be similar. I think this it is not the best solution for your case (a loop will do the trick), but maybe it will be for someone with a similar but more generic problem.

CheckBox CB2 = (CheckBox)CloneObject(CheckBox1);

//change the location here... Form1.Controls.Add(checkBoxCB2 )

private object CloneObject(object o)
{
   Type t = o.GetType();
   PropertyInfo[] properties = t.GetProperties();

   Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);

   foreach(PropertyInfo pi in properties)
      {
         if(pi.CanWrite)
           {
              pi.SetValue(p, pi.GetValue(o, null), null);
           }
      }

   return p;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜