vb.net 千位分隔符
找到的资料 但是出错
大家帮忙看看,应该怎么改?
Dim formatflg As Boolean
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If formatflg Then
formatflg = False
Exit Sub
End If
If Len(TextBox1.Text) < 4 Then
Exit Sub
End If
Dim temp As String
Dim temp2 As String
Dim leftlen As Integer
temp2 = Replace(TextBox1.Text, ",", "")
leftlen = Len(temp2) Mod 3
For i = 3 To Len(temp2) Step 3
If i = 3 Then
temp = Mid(temp2, Len(temp2) - i + 1, 3)
Else
temp = Mid(temp2, Len(temp2) - i + 1, 3) & "," & temp
End If
Next i
If leftlen <> 0 Then
temp = Left(String.Format(temp2, leftlen, 3)) & "," & temp
End If
formatflg = True
TextBox1.Text = temp
TextBox1.SelectionStart = Len(TextBox1.Text)
End Sub
[解决办法]
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case e.KeyChar
Case "0"c To "9"c, ChrW(Keys.Back), ChrW(Keys.Home), ChrW(Keys.Left), ChrW(Keys.Right)
Case Else
e.Handled = True
End Select
End Sub
Dim b As Boolean
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
'If b Then b = False : Return
Dim txt = Replace(TextBox1.Text, ",", "")
Do While txt.StartsWith("0")
txt = Microsoft.VisualBasic.Right(txt, txt.Length - 1)
Loop
Dim len = txt.Length
Dim c = len \ 3
If len < 4 Then TextBox1.Text = txt : SendKeys.SendWait("{End}") : Exit Sub
Dim temp As New StringBuilder
Dim idx As Integer = If(len Mod 3 = 0, 3, len Mod 3)
temp.AppendFormat("{0},", Mid(txt, 1, idx))
Do
If idx + 3 = len Then
temp.Append(Mid(txt, idx + 1, 3))
Else
temp.AppendFormat("{0},", Mid(txt, idx + 1, 3))
End If
idx += 3
Loop Until idx >= len
TextBox1.Text = temp.ToString
SendKeys.SendWait("{End}")
Catch ex As Exception
End Try
End Sub