VB.Net中能否通过变量名动态选择指定LineShape?
Great question! The short answer is: you can’t use the exact same approach as with Label controls, but there’s a straightforward alternative because LineShape isn’t a standard Control—it’s part of the Visual Basic PowerPacks and lives inside a ShapeContainer, not directly in your Panel’s Controls collection.
Here’s how to adapt your existing logic to work with LineShape:
First, you need to locate the ShapeContainer that holds your LineShapes (this is automatically added when you drag a LineShape onto your form, or you’ll need to create it manually if building everything dynamically).
Step 1: Get the ShapeContainer from your Panel
' Find the ShapeContainer in your Panel (assuming there's only one; adjust if multiple) Dim shapeContainer As ShapeContainer = Panel1.Controls.OfType(Of ShapeContainer)().FirstOrDefault() If shapeContainer Is Nothing Then ' Handle case where no ShapeContainer exists (create one if needed) shapeContainer = New ShapeContainer() shapeContainer.Parent = Panel1 End If
Step 2: Access a specific LineShape by name (like your Label approach)
Once you have the ShapeContainer, you can access its Shapes collection using the name of your LineShape, just like you did with Panel1.Controls for Labels:
Dim i As Integer = 0 Dim lineName As String = "VLine" & i.ToString() ' Match your LineShape naming convention ' Get the target LineShape Dim targetLine As LineShape = CType(shapeContainer.Shapes(lineName), LineShape) ' Now you can modify it, e.g.: targetLine.StartPoint = New Point(50, 50) targetLine.EndPoint = New Point(200, 200) targetLine.BorderColor = Color.Red
Step 3: (Optional) Loop through all LineShapes
If you need to iterate over all LineShapes in the container, you can do this:
For Each shape As Shape In shapeContainer.Shapes If TypeOf shape Is LineShape Then Dim line As LineShape = CType(shape, LineShape) ' Do something with each LineShape Console.WriteLine($"Found LineShape: {line.Name}") End If Next
Key difference from Label controls:
Labelinherits fromControl, so it’s stored directly in the Panel’sControlscollection.LineShapeinherits fromShape, which is not a Control—so it must be hosted inside aShapeContainer(which is a Control, hence why it’s in the Panel’sControls).
Quick note on dynamic LineShape creation:
If you’re creating LineShapes dynamically, make sure to add them to the ShapeContainer’s Shapes collection, not the Panel’s Controls:
Dim newLine As New LineShape() newLine.Name = "VLine" & i.ToString() newLine.StartPoint = New Point(10, 10) newLine.EndPoint = New Point(100, 100) shapeContainer.Shapes.Add(newLine) ' Add to ShapeContainer, not Panel1.Controls
内容的提问来源于stack exchange,提问作者Stephane

