Problem with the convert string to int in Method

Daniel_04

New member
Joined
Nov 14, 2021
Messages
4
Programming Experience
Beginner
C#:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoloAPP2._199
{
    class Product
    {

        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public int AvailableQuantity { get; set; }
        public decimal AcquisitionPrice { get; set; }
        public decimal BaseSellsPrice { get; set; }

        Menu menu = new Menu();

        private static List<Product> products = new List<Product>();   

        public void AddProduct()
        {
           Product product1 = new Product();
           Console.Write("\n\n {0,12} {1, 8}", "1", "Напишете ID на продукта ");
           product1.ProductId = int.Parse(Console.ReadLine());
         
           Console.Write(" {0,12} {1, 8}", "2", "Напишете име на продукта ");
           product1.ProductName = Console.ReadLine();

            Console.Write(" {0,12} {1, 8}", "3", "Напишете покупна цена на продукта ");
            product1.AcquisitionPrice = decimal.Parse(Console.ReadLine());

            Console.Write(" {0,12} {1, 8}", "4", "Напишете продажна цена на продукта ");
            product1.BaseSellsPrice = decimal.Parse(Console.ReadLine());

            products.Add(product1);

            Console.Write("\n\n {0,12} {1, 8}", "", "Искате ли да добавите още продукти? ");
            string chooseYN = Console.ReadLine();
            if (chooseYN == "y" ) { AddProduct(); }
            else { menu.ShowMainMenu(); }
        }

        public void ShowProducts()
        {
            int i = 1;
            foreach (Product element in Product.products)
            {
                Console.Write("\n\n {0,12} {1, 3}", i++, "");
                Console.WriteLine($"{element.ProductId, element.ProductName} ");  <<<------------- here is the mistake
            }

            Console.Write("\n\n {0,12} {1, 8}", "", "Натисни някой бутон за да продължиш" );
            string stop = Console.ReadLine();
            menu.ShowMainMenu();
        }
    }
}

How to fix this mistake? How to convert this type string in int ?
 
Last edited by a moderator:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,245
Location
Chesapeake, VA
Programming Experience
10+
You need put each thing to be printed in its own curly braces. The way you wrote it, the C# compiler was thinking that element.ProductName was your width specifier for element.ProductId. Since widths are supposed to be integers, obviously a string cannot be converted to an integer implicitly.
C#:
Console.WriteLine($"{element.ProductId}, {element.ProductName} ");

If you want to do formatting for each of elementProductId and element.ProductName, read up on C# string formatting:
 

Latest posts

Top Bottom