2013-01-02 43 views
2

我目前有一個巨大的IF語句,並希望儘量減少它。在VB中實現標籤名稱中的變量?

我有一個數據網格,我從SQL查詢填充,然後從這個數據網格我將值傳遞到單獨的標籤。

我能夠創建一個For Each循環,在該循環中,我循環查看變量,直到計數器達到7.但是,當我需要將標籤名稱值增加1時,會出現問題。每次,所以基本上我需要在標籤名稱中添加一個計數器變量。

,我需要最小化的代碼是:

result73 = DataGridView1.Rows(0).Cells(0).Value.ToString 
result74 = DataGridView1.Rows(0).Cells(1).Value.ToString 
result75 = DataGridView1.Rows(1).Cells(0).Value.ToString 
result76 = DataGridView1.Rows(1).Cells(1).Value.ToString 
result77 = DataGridView1.Rows(2).Cells(0).Value.ToString 
result78 = DataGridView1.Rows(2).Cells(1).Value.ToString 
result79 = DataGridView1.Rows(3).Cells(0).Value.ToString 
result80 = DataGridView1.Rows(3).Cells(1).Value.ToString 
result81 = DataGridView1.Rows(4).Cells(0).Value.ToString 
result82 = DataGridView1.Rows(4).Cells(1).Value.ToString 
result83 = DataGridView1.Rows(5).Cells(0).Value.ToString 
result84 = DataGridView1.Rows(5).Cells(1).Value.ToString 
result85 = DataGridView1.Rows(6).Cells(0).Value.ToString 
result86 = DataGridView1.Rows(6).Cells(1).Value.ToString 
result87 = DataGridView1.Rows(7).Cells(0).Value.ToString 
result88 = DataGridView1.Rows(7).Cells(1).Value.ToString 

If result73 = "Monday" Then 
    DaySalesLbl1.Text = result74 
ElseIf result73 = "Tuesday" Then 
    DaySalesLbl2.Text = result74 
ElseIf result73 = "Wednesday" Then 
    DaySalesLbl3.Text = result74 
ElseIf result73 = "Thursday" Then 
    DaySalesLbl4.Text = result74 
ElseIf result73 = "Friday" Then 
    DaySalesLbl5.Text = result74 
ElseIf result73 = "Saturday" Then 
    DaySalesLbl6.Text = result74 
ElseIf result73 = "Sunday" Then 
    DaySalesLbl7.Text = result74 
End If 

這個if語句繼續針對以上聲明的每個變量。我創建

的循環看起來是這樣的:

Dim cou As Integer 
Dim n As Integer 
cou = 0 
n = 1 
Do Until result74 <> "" 
    If result73 = cou Then 
     DaySalesLbl +n = result74 
    End If 
    cou = cou + 1 
    n = n + 1 
Loop 

但部分DaySalesLbl +n = result74帶來了一個錯誤,因爲它會查找生成的方法。

+0

這太好了,謝謝你的幫助。有效 :) –

回答

1

如果像我懷疑,這是一個WinForm項目,那麼您可以通過名稱使用Form.Controls集訪問控制,象這樣:

Dim cou As Integer 
Dim n As Integer 
cou = 0 
n = 1 
Do Until result74 <> "" 
    If result73 = cou Then 
     Dim l As Label = CType(Me.Controls("DaySalesLbl" & n), Label) 
     l.Text = result74 
    End If 
    cou = cou + 1 
    n = n + 1 
Loop 

Controls集合包含了所有直接子控件的形式。您可以通過索引(例如Me.Controls(0))或名稱(例如Me.Controls("DaySalesLbl6"))訪問它們。但是,集合將該列表存儲爲基類Control類型,因此在訪問特定屬性之前必須將其轉換爲特定類型。這就是爲什麼CType(..., Label)在這個例子中。

0

我會寫出如下代碼:

For i as Integer = 0 to 7 
    Select Case DataGridView1.Rows(i).Cells(1).Value.ToString 
    Case "Monday" 
     Me.Controls("DaySalesLbl" & i+1).Text = DataGridView1.Rows(i).Cells(2).Value.ToString 
    Case "Tuesday" 
     Me.Controls("DaySalesLbl" & i+2).Text = DataGridView1.Rows(i).Cells(2).Value.ToString 

    ... etc ... 

我這樣做沒有IDE,所以我希望我沒惹什麼,但我希望這將你在正確的方向和幫助。