我已经从MS power pack创建了40个左右的OvalShapes,当用户点击它们时,它们会发送一个ID给单独的函数,该函数应该改变被点击的椭圆的颜色。不幸的是,Controls
方法似乎不起作用。
Controls.Item(Dummy).fillcolor = Color.Red
给出了一个错误,说“FillColor不是'System.Windows.Forms.Control'的成员”,其中Dummy是包含控件名称的字符串。
我是VB.NET的新手,所以我不确定除了使用Controls
之外还有另一种方法可以通过字符串引用表单上的内容。谷歌并没有真正帮助解决这个问题,我发现只是在所有与椭圆型匹配的控件上使用CType
搜索所有形状的方法,当我只想改变一个控制...
编辑: 我希望能够做到以下几点:
For i = 1 to 40
OvalName = "Oval" & i
if Ovali = then do something
Next
答案 0 :(得分:2)
我不确定您是如何添加OvalShapes或您正在使用的容器类型。为了将它们添加到Windows窗体控件,您需要使用Slaks提到的shapeContainer。在这个例子中,我创建了一个shapeContainer并将其添加到Form中,然后我使用shapeContainers.Shapes.Add方法将椭圆添加到ShapeCollection Class。我还将事件处理程序附加到Ovals的Click事件,以便我可以访问调用Shape以通过EventHandler的sender对象更改其填充颜色。看看这是否适合你。
Imports Microsoft.VisualBasic.PowerPacks
Public Class Form1
Dim offset As Integer = 0
Dim OvalContainer As New ShapeContainer
Public Sub New()
' This call is required by the designer.
InitializeComponent()
OvalContainer.Size = New Size(Me.Width, 50)
Me.Controls.Add(OvalContainer)
OvalContainer.Location = New Point(0, 0)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oval As New OvalShape()
oval.Size = New Size(30, 40)
oval.Location = New Point(offset, 0)
oval.FillStyle = FillStyle.Solid
oval.FillColor = Color.Transparent
oval.BorderColor = Color.Black
oval.BorderWidth = 2
AddHandler oval.Click, AddressOf ShapeClick
OvalContainer.Shapes.Add(oval)
offset += 40
End Sub
Private Sub ShapeClick(sender As Object, e As EventArgs)
Dim oval As OvalShape = DirectCast(sender, OvalShape)
If oval.FillColor.Equals(Color.Red) Then
oval.FillColor = Color.Blue
Else
oval.FillColor = Color.Red
End If
End Sub
End Class
根据OP的澄清进行编辑
创建椭圆时添加oval.Name = "oval" & index
,这将添加将启用的名称属性
以下代码可以使用。
你可以像这样迭代Shapes Collection(这是基于我上面的例子):
For Each o As OvalShape In OvalContainer.Shapes
If o.Name = "oval1" Then o.FillColor = Color.Azure
Next
或者您可以使用ShapeContainer.Shapes.IndexOfKey
方法
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim index As Integer = OvalContainer.Shapes.IndexOfKey("oval1")
If index >= 0 Then
DirectCast(OvalContainer.Shapes(index), OvalShape).FillColor = Color.Purple
End If
End Sub
答案 1 :(得分:0)
您需要将控件转换为OvalShape
,以便您可以访问其属性:
DirectCast(Controls(Dummy), OvalShape).FillColor = Color.Red
答案 2 :(得分:0)
Dim MyOval As PowerPacks.OvalShape
For Each ThisControl As PowerPacks.Shape In ShapeContainer1.Shapes
If TypeOf (ThisControl) Is PowerPacks.OvalShape Then
MyOval = DirectCast(ThisControl, PowerPacks.OvalShape)
If MyOval.Name.ToString = ("p36") Then
MyOval.BackColor = Color.Black
End If
End If
Next