0

In my program I have two arrays which read in values from a CSV file. This CSV file has two columns. I split each column into a different array. On my form I have created a List Box called 'lbDinner', currently this is completely empty. What I im stuck on doing is adding both those arrays to the list box to be displayed for the users to choose an option.

This is all the code currently on my form, I am not sure where to go from here.

 public partial class Dinner : Form
    {
        string dinner;

        List<string> dinner_meal = new List<string>();
        List<string> dinner_price = new List<string>();

        public Dinner()
        {
            InitializeComponent();

            dinner = "..\\Debug\\Dinner.csv";
            var dinner_reader = new StreamReader(dinner);

            while (!dinner_reader.EndOfStream)
            {
                var line = dinner_reader.ReadLine();
                var values = line.Split(',');

                dinner_meal.Add(values[0]);
                dinner_price.Add(values[1]);
            }
        }

        private void Dinner_Load(object sender, EventArgs e)
        {

        }
    }

I am reading in a csv file called Dinner with the meal in the first column and the price of the meal in the second column. There is around 20 rows within this csv file.

As a summary, I want dinner_meal and dinner_price to both display in my listbox beside eachother as each dinner has its own unique price but I am not sure how to accomplish this. Thanks.

1 Answers1

2

You're going about it .. wrong.

You don't create "disjoint" collection of strings.

You create a single object. and populate properties of the object.

public class MyThingHolder

{
   public string MealName { get; set; }
   public decimal MealPrice {get; set;}
}

then, as you "read" the lines.. you populate a single MyThingHolder and put it into a

List <MyThingHolder> holders;

your code:

        while (!dinner_reader.EndOfStream)
        {
            var line = dinner_reader.ReadLine();
            var values = line.Split(',');

            MyThingHolder currentThing = new MyThingHolder() { 
                MealName = values[0],
                MealPrice = Convert.ToDecimal(values[1]) 
            };

            this.holdersAdd(currentThing);
        };

you can make a "DisplayName" ("computed") property

public class MyThingHolder

{
   public string MealName { get; set; }


   public decimal MealPrice {get; set;}

   public DisplayValue { get { return string.Format("The '{0}' costs '{1}'", this.MealName, this.MealPrice); }}

}

Then you "bind" your listbox to the holders.

Since you did not list your exact "UI" technology.... I can guess "winforms" and provide a link.

WPF, other "ui frameworks" will have different syntaxes for "binding"

But see winforms example here: https://stackoverflow.com/a/2675083/214977

granadaCoder
  • 26,328
  • 10
  • 113
  • 146