2013-07-10 60 views
-1

我試圖刪除前導零/「0」來設置飛機的標題和音高,但我會怎麼做呢?在前幾次嘗試中,我使用CInt函數將整數值轉換爲字符串值並將其轉換回整數,但這隻會產生錯誤。任何人都可以幫忙嗎?提前致謝。你會如何在vb.net中使用trimstart進行以下操作?

 Dim pitchint As Integer 
    pitchint = Pitch_txt.Text 
    If pitchint > 720 Then 
     pitchint = pitchint - 720 
     Pitch_txt.Text = pitchint 
    Else 
     If pitchint > 360 Then 
      pitchint = pitchint - 360 
      Pitch_txt.Text = pitchint 
     End If 
    End If 

    If Pitch_txt.Text.Length <> 0 Then 
     If Pitchlbl.Text <> Pitch_txt.Text Then 
      Pitchlbl.Text = Pitch_txt.Text 
     End If 
    End If 

以下是我會怎麼做,如果我想把pitchint爲一個字符串,然後返回到整數

Dim pitchint As String 
    pitchint = Pitch_txt.Text 
    pitchint = CInt(pitchint.TrimStart("0")) 
    If pitchint > 720 Then 
     pitchint = pitchint - 720 
     Pitch_txt.Text = pitchint 
    Else 
     If pitchint > 360 Then 
      pitchint = pitchint - 360 
      Pitch_txt.Text = pitchint 
     End If 
    End If 

    If Pitch_txt.Text.Length <> 0 Then 
     If Pitchlbl.Text <> Pitch_txt.Text Then 
      Pitchlbl.Text = Pitch_txt.Text 
     End If 
    End If 

沒有錯誤,因爲不是在文本框和標籤返回的值的其他是相同的,即如果我輸入070返回的值是070沒有變化。

+0

你能告訴用一個例子,你想達到什麼樣的? –

+0

你想從pitchint整數中刪除零嗎? – Killingsworth

+3

「Pitch_txt.Text」實際包含什麼?如果你使用'CInt'出錯,什麼錯誤? (「只是發現錯誤」不是對問題的描述,除非你說出你得到的錯誤是什麼。)如果這是VB.NET,爲什麼不使用'Int32.TryParse'來進行轉換從字符串到整數? –

回答

0

您的問題「070」是因爲您只處理> 360的值,並且從未在嵌套IF的末尾分配Pitch_txt.text = pitchint。是有在這裏閒着你

If pitchint > 720 Then 
    pitchint = pitchint - 720 
    Pitch_txt.Text = pitchint '<--Pitch_txt.Text was assigned 
Else 
    If pitchint > 360 Then 
     pitchint = pitchint - 360 
     Pitch_txt.Text = pitchint '<--Pitch_txt.Text was assigned 
    End If 

    'how about if pitchint=70? 
    'Pitch_txt.text was not assign with pitchint integer value 70 and will remained as "070" (string) 
End If 

我你的代碼重寫下文一個整潔的版本:

Dim pitchint As Integer 
    pitchint = Val(Pitch_txt.Text) 'simple way will filter out trailing non-numerics input 
    If pitchint > 720 Then 
     pitchint -= 720 
    ElseIf pitchint > 360 Then 
     pitchint -= 360 
    End If 

    Pitch_txt.Text = pitchint '<--put this line here will solve your "070" issue 

    If Pitch_txt.Text.Length <> 0 Then 
     If Pitchlbl.Text <> Pitch_txt.Text Then 
      Pitchlbl.Text = Pitch_txt.Text 
     End If 
    End If 
+0

完美工作,它幫助很多謝謝 –

+0

@OliverHands記得給我一個'剔'我的答案,如果解決您的問題:P – Dennis

相關問題