Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
public Product()
    {
        this.Carts = new HashSet<cart>();
    }

    public int Id { get; set; }
    public int TypeId { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

    public virtual ICollection<cart> Carts { get; set; }
    public virtual ProductType ProductType { get; set; }
} 


private Product CreateProduct()
    {
        Product product = new Product();
       
        product.Name = txtName.Text;
        product.Price = txtPrice.Text;  
        product.TypeId = Convert.ToInt32(ddlType.SelectedValue);
        product.Description = txtDescription.Text;
        product.Image = ddlImage.SelectedValue;
        
        return product;

    }


it gives an error in product.Price = txtPrice.Text; cannot implicitly convert type string to int. the datatype of price is int. please tell me if i have to convert it or change the datatype in db.
Posted
Updated 23-Dec-15 4:59am
v2
Comments
Sergey Alexandrovich Kryukov 23-Dec-15 12:07pm    
Who told you that it should "convert" it?
—SA

txtPrice.Text is a string
product.Price is an int

So yes, you have to convert the text to an integer before you assign it to the Price property

I suggest using int.TryParse() to do the conversion - see How to: Convert a String to a Number (C# Programming Guide)[^]
 
Share this answer
 
Comments
Thomas Daniels 23-Dec-15 11:02am    
+5 - beat me to it!
Sergey Alexandrovich Kryukov 23-Dec-15 12:07pm    
5ed.
—SA
The datatype of Price is int, but the one of txtPrice.Text is a string. You first have to parse txtPrice.Text to an int before you can store it in product.Price:
C#
int price;
if (int.TryParse(txtPrice.Text, out price))
{
    product.Price = price;
}
else
{
    // input could not be parsed as integer; show appropriate error message
}

More information about int.TryParse: MSDN - Int32.TryParse Method (System)[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Dec-15 12:08pm    
5ed.
—SA
Thomas Daniels 23-Dec-15 12:13pm    
Thank you!
CHill60 23-Dec-15 12:23pm    
Snap :) 5ed
Thomas Daniels 23-Dec-15 12:24pm    
Thank you!

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