2017-01-27 14 views
1

これを実行する簡単な方法がわかっていますか? a.textがnullの場合、エラーになります。私が1つずつ検出しなければ、単純なコードでa.textのヌルを0に変換できますか?文字列を整数に変換し、nullを0とする

Dim count1 As Integer = 0 
count1 = Convert.ToInt32(a.Text) + Convert.ToInt32(b.Text) + Convert.ToInt32(c.Text) 
txt_display.Text = count1 

以下のような方法で、1つずつ検出してください。

if a.Text = "" Then 
a.Text = 0 
End If 

答えて

1

1つずつ検出する必要があります。より良い方法は、独自の関数を作成することです。以下を試してください。

Dim count1 As Integer = 0 
count1 = ConvertToInteger(a.Text) + ConvertToInteger(b.Text) + ConvertToInteger(c.Text) 
txt_display.Text = count1 




Private Function ConvertToInteger(ByRef value As String) As Integer 
    If String.IsNullOrEmpty(value) Then 
     value = "0" 
    End If 
    Return Convert.ToInt32(value) 
End Function 
1

例:

If String.IsNullOrEmpty(a.Text) Then 
a.Text = "0" 
End If 
1

あなたの目的は、あなたは、単にInt32.TryParseを使用することができ、あなたのテキストボックス内の値を合計して整数に変換できないテキストボックスを無視する場合。
例外をスローせずにテキストを整数に変換できない場合は、変数を0に設定します。

' In place of your textboxes 
Dim x1 As String = "2" 
Dim x2 As String = Nothing 
Dim x3 As String = "5" 

Dim a, b, c As Integer 

Int32.TryParse(x1, a) 
Int32.TryParse(x2, b) 
Int32.TryParse(x3, c) 

Dim result = a + b + c 
Console.WriteLine(result) 

間違った入力をユーザーに知らせるために、テキストボックスのテキストに「0」の文字列を書きたい場合は代わりに、あなたは再びInt32.TryParse

を使用して、テキストボックスを一つずつ確認する必要があり
Dim value1 as Integer 
if Not Int32.TryParse(a.Text, value1) Then 
    a.Text = "0" 
End If 

' Here the variable value1 contains the converted value or zero. 
' repeat for the other textboxes involved 
関連する問題