How to convert this from vb to csharp

A

Aaron Prohaska

Can anyone tell me how I can convert the following code to csharp? I'm
having problems with this because it seems as though KeyChar.IsDigit
doesn't exist in csharp.

----------------------------------------------------
Private Overloads Sub TextBox1_TextChanged(ByVal sender As
System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Handles TextBox1.KeyPress
Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar)
Dim isDecimal As Boolean = e.KeyChar.ToString = "."
If Not isKey And Not isDecimal Then
e.Handled = True
End If
End Sub
----------------------------------------------------

Regards,

Aaron Prohaska

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-
Wrench Science Inc.
http://www.wrenchScience.com/
Phone: 510.841.4748 x206
Fax: 510.841.4708
-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-
 
J

Jon Skeet [C# MVP]

Aaron Prohaska said:
Can anyone tell me how I can convert the following code to csharp? I'm
having problems with this because it seems as though KeyChar.IsDigit
doesn't exist in csharp.

It's a static method in the Char class. It's an aberration (IMO) that
you can call it "on" a specific character in VB.NET. In C#, static
methods can't be called using references - they have to use the
typename (unless they're in the current class or an ancestor, of
course).

So, you'd have:

bool isKey = Char.IsDigit(e.KeyChar);
bool isDecimal = e.KeyChar.ToString()==".";

if (!isKey && !isDecimal)
{
e.Handled = true;
}

However, I'd write the isDecimal test as:

bool isDecimal = (e.KeyChar=='.');

or actually just inline both:

if (!Char.IsDigit(e.KeyChar) &&
e.KeyChar != '.'))
{
e.Handled = true;
}
 
J

Jimi

First, I changed one line to:
Dim isKey As Boolean = char.IsDigit(e.KeyChar)

Then I ran it through the Instant C# VB to C# converter:

//INSTANT C# TODO TASK: Insert the following converted event handlers
at the end of the 'InitializeComponent' method for forms or into a
constructor for other classes:
//TextBox1.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(TextBox1_TextChanged);

private void TextBox1_TextChanged(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
bool isKey = char.IsDigit(e.KeyChar);
bool isDecimal = (e.KeyChar.ToString() == ".");
if (! isKey & ! isDecimal)
{
e.Handled = true;
}
}
 

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

Similar Threads


Top