Click here to Skip to main content
15,888,052 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
private Product CreateProduct()
    {
        Product product = new Product();

        product.Name = txtName.Text;
        product.Price = Convert.ToDouble(txtPrice.Text);
        product.TypeID = Convert.ToInt32(ddlType.SelectedValue);
        product.Description = txtDescription.Text;
        product.Image = ddlImage.SelectedValue;

        return product;
    }


What I have tried:

I've tried Convert.ToInt32(txtPrice.Text);, but that doesnt work either
Posted
Updated 17-Mar-17 9:09am
Comments
[no name] 17-Mar-17 12:30pm    
That's because you should be using Double.TryParse instead.

Try:
C#
double price;
if (!double.TryParse(txtPrice.Text, out price))
   {
   // Report input problem to user.
   ...
   return;
   }
product.Price = price;
If Price is an integer - and it probably shouldn't be - then try:
C#
double price;
if (!double.TryParse(txtPrice.Text, out price))
   {
   // Report input problem to user.
   ...
   return;
   }
product.Price = (int) price;
Never use Convert.To... to handle user input: it always throws an exception on bad values, and users make mistakes all the time. If you had filled out a form with a whole bunch of data, and the app then crashed because you types "," instead of "." you'd be pretty annoyed - so allow users to make mistakes and get them to correct them!
 
Share this answer
 
Hmmmmm. I been thinking, since the Textbox name is txtPrice, I was wondering if the box is holding string with currency format like (£12.30). If that the case, try follow the below example

C#
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-GB");
    string txtPrice = "£12.30";
    double price;
    double.TryParse(txtPrice, System.Globalization.NumberStyles.AllowThousands |
      System.Globalization.NumberStyles.AllowDecimalPoint |
      System.Globalization.NumberStyles.AllowCurrencySymbol, provider, out price);
    product.Price = price;

Output: 12.3
if price is an integer
C#
product.Price = (int)price;

Output: 12
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900