vb.net在控件之间传递变量

时间:2013-11-25 01:11:56

标签: vb.net

这是我的代码

Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each fi As FileInfo In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
        Dim pictooltip As New ToolTip
        Dim pbx As New Button
        AddHandler pbx.Click, AddressOf pbx_click
        pbx.Width = 150
        pbx.Height = 150
        pbx.BackgroundImage = Image.FromFile(fi.FullName)
        wallpapers.Controls.Add(pbx)
        pbx.Cursor = Cursors.Hand
        pictooltip.SetToolTip(pbx, fi.Name)
        pbx.BackgroundImageLayout = ImageLayout.Stretch

    Next
End Sub

Private Sub pbx_click()
    main.BackgroundImage = Image.FromFile(fi.FullName)
End Sub

我无法想象如何在pbx_click()

中使用“fi”

任何暗示?

4 个答案:

答案 0 :(得分:2)

只需将FullName()放入Button的Tag()属性中,并在单击时将其拉出:

Dim pbx As New Button
pbx.Tag = fi.FullName

把它拉出来:

Private Sub pbx_click()
    main.BackgroundImage = Image.FromFile(DirectCast(sender, control).Tag.ToString())
End Sub

答案 1 :(得分:0)

试试这个,

Public Class Form1

Dim fi as FileInfo

Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each Me.fi In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
        Dim pictooltip As New ToolTip
        Dim pbx As New Button
        AddHandler pbx.Click, AddressOf pbx_click
        pbx.Width = 150
        pbx.Height = 150
        pbx.BackgroundImage = Image.FromFile(fi.FullName)
        wallpapers.Controls.Add(pbx)
        pbx.Cursor = Cursors.Hand
        pictooltip.SetToolTip(pbx, fi.Name)
        pbx.BackgroundImageLayout = ImageLayout.Stretch

    Next

End Sub

Private Sub pbx_click()
    main.BackgroundImage = Image.FromFile(fi.FullName)
End Sub

End Class

答案 2 :(得分:0)

将您的活动更改为:

Private Sub pbx_click(sender As Object, e As System.EventArgs)
    main.BackgroundImage = Image.FromFile(DirectCast(sender, Button).BackgroundImage)
End Sub

或者,您可以使用Tag属性并存储一些序列化数据。见这里:Add parameter to Button click event

答案 3 :(得分:0)

您的Fi在第一个子例程(或子)中本地声明。

在Personalize_Load子项之外声明Fi,然后将数据传递给它。

 Dim fi as String = ""

Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each fii As FileInfo In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
    Dim pictooltip As New ToolTip
    Dim pbx As New Button
    AddHandler pbx.Click, AddressOf pbx_click
    pbx.Width = 150
    pbx.Height = 150
    pbx.BackgroundImage = Image.FromFile(fii.FullName)

    fi = fii.FullName

    wallpapers.Controls.Add(pbx)
    pbx.Cursor = Cursors.Hand
    pictooltip.SetToolTip(pbx, fi.Name)
    pbx.BackgroundImageLayout = ImageLayout.Stretch

    Next
 End Sub

Private Sub pbx_click()
    main.BackgroundImage = Image.FromFile(fi)
End Sub

然后你可以通过在任何子上调用pbx_click(),或者尝试将其用于处理程序来使用pbx_click()。