2013-11-02 54 views
0

我想要使用發送給SetSectorImage子的Sector變量來命名正在更改的圖像(圖像確實已存在於Web表單上,我只是更改了URL)。谷歌搜索只讓我在MSDN上的一篇關於CallByName方法的文章,但我不知道它是否會在這種情況下發揮作用,我不知道它是如何工作的。如何在不知道ID的情況下更改圖片的屬性?

這裏的文章,如果有幫助: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 
+0

訪問他們,我相信有一些像'Page.FindById(Sector)' –

回答

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) 
+0

這對使用CallByName有沒有優勢? –

+0

@TrevorRowe:'FindControl'是ASP.NET的標準部分。 'CallByName'更底層(基於[Reflection](http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx))。 「反射」通常會比較慢。 'CallByName'是通用的,並且可以工作,但是當有歧義時(例如同名的字段和變量)可能會有意想不到的結果。 – IvanH

0

我做了CallByName()一些更多的研究,我發現我可以在這種情況下使用它。改變圖像的URL行是:

CallByName(Sector, "ImageUrl", CallType.Set, "~/Images/" + SectorStatus) 
相關問題