2015-01-14 60 views
0

問題:我想更改某些固定命名按鈕上的文本。根據變量名稱更改按鈕文本

當我運行例程時,我可以看到vButtonName是正確的,但Dim Button As Button沒有提取值?!

,如果我硬編碼按鈕的名稱我已經把第一的.aspx.vb代碼,然後在.aspx按鈕代碼

文本的變化。

.aspx.vb代碼:

Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQL_DEMO").ToString() 

For i As Integer = 0 To arr.Count - 1 
    Using connection = New SqlConnection(ConnectionString) 
     Using command As New SqlCommand("SELECT COUNT(OverallRiskCategory) FROM TblAsbestos WHERE OverallRiskCategory = @Category", connection) 
      ' Open your connection '  
      connection.Open() 

      ' Add your parameter ' 
      command.Parameters.AddWithValue("@Category", arr(i).ToString()) 

      ' Execute your query ' 
      Dim result = command.ExecuteScalar() 

      Dim vButtonName As String = "btnRiskRatingFilter" & arr(i).ToString() & "Text" 

      Dim button As Button = FindControl(vButtonName) 

      If Not button Is Nothing Then 
       button.Text = String.Format("Class " & arr(i).ToString & " (" & result & ")") 
      End If 

      connection.Close() 
     End Using 
    End Using 
Next 

的.aspx代碼:

<asp:Button ID="btnRiskRatingFilterAText" runat="server" Text="Class A" CssClass="ButtonTextual" OnCommand="btnRiskRating_Click"/> 
+1

你可能需要添加它標註了合適的ASP標籤 – Plutonix

+0

vb.net,你還在想什麼?編輯:完成:-) – indofraiser

+2

我沒有看到任何錯誤。你100%確定你生成的名字是否正確?您的按鈕是由代碼隱藏創建還是全部包含在您的aspx頁面中?而VB.NET並不總是ASP.NET,它可能是從控制檯應用程序到服務的任何內容......所以來自Plutonix的評論是正確的 –

回答

1

好了,所以我不得不改變的FindControl找到主控那麼contentholder:

Dim button As Button = Master.FindControl(「ContentPlaceHolder1」)。Fin dControl(vButtonName)

編輯:我還更新了代碼,每個註釋,以提高連接口的佈局/關閉

Dim arr As New ArrayList 
     arr.Add("A") 
     arr.Add("B") 
     arr.Add("C") 
     arr.Add("D") 
     arr.Add("NA") 
     arr.Add("UN") 

     ' Try 

     Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQL_DEMO").ToString() 
     Using connection = New SqlConnection(ConnectionString) 
      ' Open your connection '  
      connection.Open() 
      For i As Integer = 0 To arr.Count - 1 
       Using command As New SqlCommand("SELECT COUNT(OverallRiskCategory) FROM TblAsbestos WHERE OverallRiskCategory = @Category", connection) 
        ' Add your parameter ' 
        command.Parameters.AddWithValue("@Category", arr(i).ToString()) 
        ' Execute your query ' 
        Dim result = command.ExecuteScalar() 
        Dim button As Button = Master.FindControl("ContentPlaceHolder1").FindControl("btnRiskRatingFilter" & arr(i).ToString() & "Text") 

        If Not button Is Nothing Then 
         button.Text = String.Format("Class " & arr(i).ToString & " (" & result & ")") 
        End If 
       End Using 
      Next 
      connection.Close() 
     End Using 

     'Catch ex As Exception 
     'btnRiskRatingFilterAText.Text = "Unable to load" 
     ' End Try