2015-04-16 47 views
0

我不是在vb.net太好,主要是用C#的工作,我會需要一些vb.net專家幫我這個foreach循環:我如何解決編譯器錯誤的VB「If`語句中的「預期語句結束」

Dim pSources() As Integer = {} 
pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId) 

Try 

    For Each intSelect As Integer In pSources 

     For Each li As ListItem In chkSources.Items 

      If Convert.ToInt32(li.Value) Equals(intSelect) 
       li.Selected = True 
      End If 

     Next 

    Next 

Catch ex As Exception 

End Try 

我想pSources陣列的Integer在檢查每個項目,找到複選框的列表中選擇合適的值,並檢查值匹配的複選框。

隨着我在這一刻我就行收到錯誤的代碼,我做的,如果比較,這就是錯誤:

End of statement expected

任何想法,我怎麼能解決這個問題?

或者,也許更好,我該如何使用LINQ的聲明,將檢查值,然後選中複選框如果值包含在pSources陣列英寸

+0

你真的應該看看的格式代碼並嘗試格式化for循環以正確的方式嵌套..意味着語句的匹配結束位置..這在視覺上是相當明顯的 – MethodMan

+1

您是否需要'Then'和'If',爲什麼要嘗試/在那裏抓到? –

+0

,如果你是在一個子是哪裏結束子..?這裏是一個偉大的教程,你可以看看http://www.tutorialspoint.com/vb.net/vb.net_foreachnext_loops.htm還我建議你看一下如何格式化程序功能等。 – MethodMan

回答

0

這裏就是我會做我自己......

下面的代碼檢查,以確保pSources的東西,也有它的東西。試圖做一個比較之前的Integer.TryParse不會拋出一個異常,如果它不能解析,並會短路...

Dim pSources As New List(Of Integer) 
Dim intNumber As Integer = 0 
pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId) 

Try 
    If pSources IsNot Nothing AndAlso pSources.Count > 0 Then 
     For Each intSelect In pSources 
     For Each li As ListItem In chkSources.Items 
     If Integer.TryParse(li.Value.ToString, intNumber) AndAlso (intNumber = intSelect) Then 
      li.Selected = True 
     End If 
     Next 
     Next 
    End If 

Catch ex As Exception 
    'Handle your exception... 
End Try 
+1

我喜歡'.TryParse'的單行語法,後面跟着'AndAlso(predicate)'。漂亮的構造。 –

1

你的IF語句需要一個「然後」在它的結束。在線上有一些體面的C#到VB.NET轉換應用程序(例如code converter from Telerik) - 您可以嘗試其中的一些來幫助您熟悉VB.NET。

3

兩個問題,我看到:

1)像拉斯指出,需要IfThen聲明。在VB中,語法是

If <boolean statement> Then 
    <Some Code> 
End If 

2)我沒有看到一個.在布爾語句將Equals。這只是無效的語法。 Like在評論中提到,您可以在此處使用=運算符以獲得更多清晰度。如果你仍然想使用Equals然後添加一個.Converter.ToInt32(li.Value)Equals之間。您的最終代碼應該是下面:

Dim pSources() As Integer = {} 
pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId) 

Try 

    For Each intSelect As Integer In pSources 

     For Each li As ListItem In chkSources.Items 

      If Convert.ToInt32(li.Value).Equals(intSelect) Then 
       li.Selected = True 
      End If 

     Next 

    Next 

Catch ex As Exception 

End Try 
+0

'pSources'可能什麼都不是,應該在嘗試使用該對象之前進行檢查。你不需要明確地說'As Integer',因爲'pSources'是一個'Integers'的數組,不需要的時候就可以再次投射它。 'Convert.ToInt32'會拋出一個異常,如果它不是'Integer' ...只是幾個建議... – Codexer

+0

我建議的解決方案只是對提問者原始代碼的修改,而不是我如何處理它。此外,pSources不能是'Nothing',因爲它既是用'{}'初始化的,又重新設置了下一行。 – mclark1129

+0

如果調用SCCC.GetSources(SysCompany,SysUser,ccHeaderId)不返回任何內容,kaboom!你不能總是依賴函數來返回一些東西...... – Codexer

0

此:

Dim pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId) 

    Dim val = 0 
    For l = 0 To chkSources.Items.Count - 1 
     chkSources.SetSelected(l, Integer.TryParse(chkSources.Items(l).ToString, val) AndAlso pSources.Contains(val)) 
    Next