VB.Net Selecting LineShape

529 views Asked by At

In Vb.Net, I'm dynamically creating several textbox and labels. I'm naming them ex. VLabel1, VLabel2, VLabel3 ... and then I use CType and a variable to use them.

Dim VarName as String
Dim i as Integer
Dim MyLabel as Label

i=0
VarName = ("VLabel" & i.ToString)
MyLabel = CType(Panel1.Controls(VarName), Label)

Now I'm adding lines using LineShape (I can't use label having height of 1 because my lines are diagonals). Can I use a similar way to select a specific line or do I have to use a loop in my ShapeContainer and compare names until I find the one I want?

Thank you,

Stephane

2

There are 2 answers

0
Joel Coehoorn On

do I have to use a loop in my ShapeContainer and compare names until I find the one I want?

What do you think the Controls(VarName) does? It has to lookup the control by name, too. If you're comfortable with that, you can write a method in your form that does the same thing.

But a better option for both the LineShapes and the Labels is use List(Of LineShape) and a List(Of Label). When you create a dynamic control and add or remove it from your form, also add or remove it form your list. Then you can reference these items by index, without needing to build a name string. You'll also have less casting this way.

0
tinstaafl On

Another option to index them by name is to use Dictionary(Of String,Lineshape) and Dictionary(Of String, Label). A couple of helper subs can handle adding/removing where needed and adding/removing to the appropriate Dictionary. With this you also eliminate the need for casting as the actual objects are of the correct type already.

Even better yet, since Shapes aren't part of the standard library, I would suggest learning how to draw the lines directly on to your form.

I've never done it, but it should be possible to actually create the lines as controls, by creating a class that inherits from the Control class and overriding the Paint sub to draw the line.