After reading your comments, it seems that you have several problems in your code.
On the one hand, in your TextBox
ganancia
you apparently have a symbol %
. With that symbol you will not be able to convert the text to float
, so you must delete it when passing it to the function Parse
.
On the other hand, if the Culture configured in your system is Spanish, it will not recognize the point as a decimal separator (since in English the decimal separator is the ,
, the point is used as a thousand separator), so use CultureInfo.InvariantCulture
for the point to be considered a decimal separator. So that line should look like this:
ganancia = float.Parse(txtganancia.Text
.Replace("%", ""), System.Globalization.CultureInfo.InvariantCulture);
It's also interesting to use TryParse
instead of Parse
, so you do not get an exception if you can not convert the text.
Finally, when it comes to working with currency, the appropriate type is never float
, but decimal
. If you do not use it, you can have several problems associated with floating point math.
With all these changes, your code should look like this:
database.SoloNumeros(e);
if (e.KeyChar == Convert.ToChar(Keys.Enter))
{
decimal pventa, pcompra, ganancia;
if (!decimal.TryParse(txtcompra.Text,
System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture,
out pcompra))
{
MessageBox.Show("Error al convertir Precio de compra a decimal");
}
else
{
if (!decimal.TryParse(txtganancia.Text
.Replace("%", ""),
System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture,
out ganancia))
{
MessageBox.Show("Error al convertir Porcentaje de ganancia a decimal");
}
else
{
pventa = pcompra * (1 +(ganancia/100));
txtventa.Text = pventa.ToString();
}
}
}