Si estas usando textBox para recibir datos que solo pueden ser numéricos, probablemente este codigo te servirá.
Necesitas una funcion (en este caso llamada IsDigit)
public static bool isDigit(KeyPressEventArgs e, string texto)
{
bool IsDec = false;
int nroDec = 0;
try
{
if (e.KeyChar ==
{
return false;
}
for (int i = 0; i < texto.Length; i++)
{
if (texto[i] == '.')
{
IsDec = true;
}
if (IsDec && nroDec++ >= 2)
{
return true;
}
}
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
return false;
}
else
{
if (e.KeyChar == 46)
{
if (IsDec)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
Para usarla, en el evento KeyPress del textBox, pones lo siguiente:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = isDigit(e, textBox.Text);
}
Eso te permite meter solo números y un punto con dos decimabesl. Probablemente no sea la función mas optima, pero a mi me funciona bien.
El código lo encontré en la web del Guille.
Actualmente estoy trabajando en un proyecto que incluye un punto de venta.