one decimal point in text box

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
 
S

Stefan Schelling

Hi Trawlerman

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

Stefan Schelling
 
T

trawlerman

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top