one decimal point in text box

  • Thread starter Thread starter trawlerman
  • Start date Start date
T

trawlerman

Hi all,
C# newbie after migrating from VB. I wish to have only valid numbers
entered into a txtbox . i.e only one decimal point.

///////////////////My VB code for this is:
Private Sub txtGcost_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 48 To 57, 8
Case 46
If InStr(txtGcost.Text, ".") > 0 Then
'Decimal point already there.
KeyAscii = 0
If Left(txtGcost.Text, 1) = "." Then
txtGcost = "0."
End If
End If
Case Else
KeyAscii = 0
End Select
End Sub


///////////////My C# code is:


private void txtCost_KeyPress(object sender, KeyPressEventArgs e)
{
{
const char Delete = (char)8;
const char dot = (char)46;
string check4dot = ".";
string searchstring = txtCost.Text;
int checkit = searchstring.IndexOf(check4dot);


if (checkit >1 )


{


e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar
!= Delete && e.KeyChar != dot;


Which works fine, except for not allowing no more than one decimal
point,


Thank in advance
 
Hi Trawlerman

Why don't you validate with a RegularExpression if the text in your Textbox
is valid?

Stefan Schelling
 
Stefan Schelling wrote:
Hi Stefan
Yes i think that would be a more logical approach. Let them type in
what they want and then catch an exception at event time.
Thanks
 
Back
Top