如何在不知道其ID的情况下更改图像的属性?

时间:2013-11-02 04:37:44

标签: asp.net vb.net

我想使用发送到SetSectorImage子的Sector变量来命名正在更改的图像(图像已存在于Web表单上,我只是更改URL)。谷歌搜索只引导我在MSDN上发表一篇关于CallByName方法的文章,但我不知道它是否会在这种情况下起作用,而且它会如何,我无法弄清楚如何。

这篇文章如果有帮助:http://msdn.microsoft.com/en-us/library/22x2chfx.aspx

Imports System
Imports System.IO

Public Class Launcher
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetSectorImage("Sector1")
        SetSectorImage("Sector2")
        SetSectorImage("Sector3")
    End Sub

    Sub SetSectorImage(Sector As String)
        Dim SectorStatus As String
        Try
            Using Reader As New StreamReader(Sector + ".txt")
                SectorStatus = Reader.ReadToEnd()
                Reader.Close()
                Sector_SHOULD_BE_USED_HERE.ImageUrl = ("~/Images/" + SectorStatus)
            End Using
        Catch ex As Exception
            ErrorMessage.Text = ("There was an error reading the status of: " + Sector)
            ErrorMessage.Visible = True
        End Try
    End Sub

End Class

2 个答案:

答案 0 :(得分:0)

我对CallByName()做了一些研究,发现我可以在这种情况下使用它。更改图片网址的行将是:

CallByName(Sector, "ImageUrl", CallType.Set, "~/Images/" + SectorStatus)

答案 1 :(得分:0)

假设您在页面上有图片:

<asp:Image ID="Sector1" />
<asp:Image ID="Sector2" />
<asp:Image ID="Sector3" />

您可以使用Control.FindControl Method

访问它们
Dim myControl1 As Control = FindControl(Sector)
Dim myImage As Image = myControl1
myImage.ImageUrl = ("~/Images/" + SectorStatus)