KeyPress Event

  • Thread starter Thread starter DrewT1755
  • Start date Start date
D

DrewT1755

Guest
I have a key press event for a text box that only allows for digits, backspace, decimals and prevents multiple decimals and it works fine. Below is my event.

// This allows for backspace (46) and prevents mutiple decimals.
char ch = e.KeyChar;
if (ch == 46 && this.ActiveControl.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
// This allows for only numbers, decimals and backspace.
e.Handled = !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != (char)Keys.Back;

I would like to create a class for this code so that I could call it from the Key Press Event for any text box that I want to treat as a numeric field. Below is my class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NBSUtilityBilling
{
class Utilities
{

public void NumericKeyPress(object sender, KeyPressEventArgs e)
{
// This allows for backspace (46) and prevents mutiple decimals.
char ch = e.KeyChar;
if (ch == 46 && this.ActiveControl.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
// This allows for only numbers, decimals and backspace.
e.Handled = !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != (char)Keys.Back;
}
}
}

The above class gives me the error: 'Utilities' does not contain a definition for 'ActiveControl' and no extension method accepting a first argument of type 'Utilities' could be found (are you missing a using directive or an assembly reference?)

I am new to this so any help would be appreciated.

Thank you.



DrewT1755

Continue reading...
 
Back
Top