2015-10-13 28 views
0

我想要限制用戶只傳遞數字,字母, - 和單個空間。問題是,我不想遇到這樣的情況,用戶可以把一個以上的空間,在同一個地方象下面這樣:在同一地點檢查空間的發生

Something 45 Last Ter 

正如你看到的,我們有一個以上的空間已經被放置後的兩個地方「某事「和」最後「之後。我怎樣才能改變我的代碼以確保這種情況不會發生?

'check whether Symbol contains only letters, digits or - symbol otherwise break             
For Each c As Char In txtNazwa.Text 
    If Not Char.IsLetterOrDigit(c) AndAlso c <> "-"c AndAlso c <> " " Then 
     MessageBox.Show("Only letters, digits, - and single space are available", "Ostrzeżenie", MessageBoxButtons.OK, MessageBoxIcon.Warning) 
     Exit Try 
    End If 
Next 
+3

,你可以使用'與string.replace(「‘’」)'和解決它,而不是打擾他們 – Plutonix

+3

格式吃它,而是用2位的第一個參數,1第二和任何多空格將被轉換...'String.Replace([2 spaces],[1 space]「)' – Plutonix

回答

2

直接回答這個問題:

檢查如果字符串包含連續的2個空格這樣的:

If txtNazwa.Text.Contains(" ") Then 
    MessageBox.Show("The value must not contain two consecutive spaces") 
End If 

相反,如果你想解決這個問題的用戶,可以這樣做:

Dim str As String = txtNazwa.Text 

While str.Contains(" ") 
    str = str.Replace(" ", " ") 
End While 

txtNazwa.Text = str 
+0

好吧但如果他把3或4或更多的空間呢?我這樣做,但然後我將不得不復制這個方法.. – Arie

+0

@StackUser,它也可以工作,因爲3個空格包含2個空格 –

1

使用正則表達式,並保持自己的麻煩。

Dim Nazwa_Text = System.Text.RegularExpressions.Regex.Replace(txtNazwa.Text, "\s+", " ") 

接下來使用您的For-Loop,如您的帖子中所述。

3

我假設用戶正在輸入一個文本框。看看文本框更改事件。

private void currencyTextBox_TextChanged(object sender, EventArgs e) 
{ 
    try 
    { 
     currencyTextBox.Text = Regex.Replace(currencyTextBox.Text, " {2 }", " ") 
    } 
    catch 
    { 
     // Do something if we get an error 
    } 
} 
+1

好主意檢查爲用戶類型 –