Search code examples
c#arraystostring

ToString override to return array


I wanted to make a wpf program that when you click the Generate button the class SSales will get/store the arrays of values to the class then return it to the listbox. New here. Sorry.

   private void GenerateButton_Click(object sender, EventArgs e)
   {
        Random rand = new Random();

        int[] year = { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 };

        double[] Sales = new double[10];

        for (int i = 0; i < 10; i++)
        {
            Sales[i] = rand.Next(1000, 50000);

        }

        SSales yearSale = new SSales(year, Sales);

        for (int j = 0; j < 10; j++){

        //I want the listbox to display the values of yearSale.Year and yearSale.Sales

            listBox1.Items.Add(yearSale);
        }
    }

public class SSales
{
    public int[] Year { get; set; }
    public double[] Sales { get; set; }

    public SSales(int[] iYear, double[] dSales)
    {
        Year = iYear;
        Sales = dSales;
    }

    public override string ToString()
    { 
       //I'm trying to make this format "2001     $25,000.00" then return it to listbox

        return string.Format("{0}\t\t{1:C0}", Year, Sales);  
    }

}

Solution

  • Since you are adding 10 SSales objects to the ListBox, each object should accept a single int and a single double:

    public class SSales
    {
        public int Year { get; set; }
        public double Sales { get; set; }
    
        public SSales(int iYear, double dSales)
        {
            Year = iYear;
            Sales = dSales;
        }
    
        public override string ToString()
        {
            return string.Format("{0}\t\t{1:C0}", Year, Sales);
        }
    }
    

    Try this:

    private void GenerateButton_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
    
        int[] year = { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 };
    
        double[] Sales = new double[10];
    
        for (int i = 0; i < 10; i++)
        {
            Sales[i] = rand.Next(1000, 50000);
        }
    
        for (int j = 0; j < 10; j++)
        {
            listBox1.Items.Add(new SSales(year[j], Sales[j]));
        }
    }