Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
First of all, sincere thanks to Wayne Gaylard for introducing me to the concept of lists. I was just working on this small "car garage" application using wpf, trying to implement lists but I am struck and don't know how to proceed further. This is what i have so far. I am a very beginner to programming, so please forgive my lack of good design.

In car.cs
C#
class car
    {

        public double cylinders
        {
            get;
            set;
        }

        public double topspeed
        {
            get;
            set;
        }

        public double horsepower
        {
            get;
            set;
        }
    }


In Window1.cs

public partial class window1 : Window
    {
        int n;
        int i = 0;
         List<car> carlist = new List<car>(); 
         car newCar = new car();

 //I have created the list and newcar object here, but could not define newcar properties because of some error "it is a type but used like a field", and thus have defined them below
 
// Also, I would like to create a number of newcars according to the input in textBox1.text (number of cars)       
        public window1()
        {
            InitializeComponent();
        }
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            n = Convert.ToInt32(textBox1.Text);   // number of cars (The number of newcar objects to be created should depend on this textbox value)
            if (i < n)
            {
                newCar.cylinders = double.Parse(textBox2.Text);
                newCar.topspeed = double.Parse(textBox3.Text);
                newCar.horsepower = double.Parse(textBox4.Text);
                carlist.Add(newCar);
                textBox2.Clear();
                textBox3.Clear();
                textBox4.Clear();
                i++;
            }
                if (i == n)
                {
                    MessageBox.Show("please enter garage");
                }
            
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            window2 win2 = new window2();
            win2.Show();
        }
    }


and in Window2.cs

C#
private void button1_Click(object sender, RoutedEventArgs e)
      {
          foreach (car item in carlist) // I cannot use this list because it is in another window. 
// I would either like to create a newcarlist in window2 and copy all the contents of the carlist in window1 or need a way to access the carlist in window1. 
          {
              MessageBox.Show(string.Format("Topspeed: {0}, Horsepower: {1} and so on", item.cylinders, item.topspeed, item.horsepower, ));  // display topspeed, horsepower, cylinders of each car.
           }

      }
  }




Any help in fixing this code would be greatly appreciated. thanks
Posted
Updated 9-Sep-11 4:51am
v6

If I understood your questions correctly:

First of all the list should be defined at module level (at least). If you define the list in a click event handler, you cannot access it in another method. So at module level something like:
C#
public partial class Window1 : Window {

   private List<car> carlist = new List<car>();

...</car></car>


Here you can set the properties when creating an instance:
C#
carlist.Add((new car()
                {
                   cylinders = 8, horsepower = 420...
                });

Or you can set them separately:
C#
car newCar = new car();
newCar.cylinders = 8;
newCar.horsepower = 420;
...
carlist.Add(newCar);


You can also set the properties from a user control, something like:
C#
...
newCar.horsepower = int.Parse(txtHorsePower.Text);
...

When you loop through the cars, you can use foreach. Something like:
C#
private void button1_Click(object sender, RoutedEventArgs e) //"click to view cars' details" is the name button1 in window2
        {
            /*when click to view button is clicked a list of message boxes should appear
            one after the other showing details of everycar*/
            foreach (car item in carlist)
            {
                MessageBox.Show(string.Format("Topspeed: {0}, Horsepower: {1} and so on", item.topspeed, item.horsepower);  // display topspeed, horsepower, cylinders of each car.
             }
        }
 
Share this answer
 
Comments
Mehdi Gholam 9-Sep-11 10:19am    
My 5!
Wendelius 9-Sep-11 11:04am    
Thanks :)
steersteer 9-Sep-11 10:34am    
Thank you very much for the reply. I have done as you've recommended, but I am afraid I have a few problems in it. I will update the whole question. Please go through it and let me know your solution. Much appreciated.
steersteer 9-Sep-11 10:52am    
I have updated my question. Please let me know what you think about it.
Wendelius 9-Sep-11 11:04am    
Basically looks fine. However, you donät have to create a new instance of the car at module level, so you can move

car newCar = new car();

into the Button1_Click, inside the if (i < n) . This way yo always instantiate a new car when button1 is pressed. Currently you instantiate just 1 car and if you press Button1 several times you actually change the properties of the same car (instance).

Do you have some specific problems with the newest version (other than what I mentioned in this comment?
OK, to add cars to your List

C#
double noCylinders;
double topSpeed;
double horsePower;
double.TryParse(textBox2.text,out noCylinders);
double.TryParse(textBox3.text,out topSpeed);
double.TryParse(textBox4.text,out horsePower);
b.Add(new Car()
{
   //don't know how to proceed
   cylinders = noCylinders,
   horsepower = horsePower,
   topspeed = topSpeed
});


and then to view each car ike this

C#
foreach(Car car in b)
                {
                    MessageBox.Show("Cylinders = " + car.cylinders +"\n" + "Horsepower = " + car.horsepower + "\n" + "Top speed = " + car.topspeed)
                }


Just a word on naming convention

All classnames should start with a capital, as well as all properties within a class like this

C#
class Car
    {
        public double Cylinders
        {
            get;
            set;
        }

        public double TopSpeed
        {
            get;
            set;
        }

        public double Horsepower
        {
            get;
            set;
        }



Hope this helps
 
Share this answer
 
Comments
steersteer 9-Sep-11 10:46am    
Thanks. I have updated my question now. Please take a look at it and let me know. Thanks again for the tip on naming convention. will follow it from now.
First of I don't feel it's a good idea to use WPF while learning how to program, so I suggest you forget about WPF and start doing some basic console applications. trying to learn WPF while is not a good idea, I know good programmers who have had trouble learning WPF or think they have learned it but really doesn't have any idea of how to utilize WPF. I'm not trying to be a troll, I'm just afraid you're going to choke yourself by trying to learn to much at the same time.

That said I'll go through some of the problems you have in your code.
1)
C#
b.Add((new car()
{
   //don't know how to proceed  
});

What you're trying to do here is using the Object initializer[^]
So you can initialize the properties of your type car, like this:
C#
b.Add((new car()
{
   cylinders = 6.0,
   topspeed = 500.0, // Fast car :P assuming this is kph or mph and not
                     // meters-per-hour :)
   horsepower = 1000.0 
});


2) In Button1_Click you create a new list to which you add a new car with the code we just discussed. But you do not store this list anywhere, what you probably want is to have a field in your class where you can store your car instances.

3) Again in Button1_Click you have this statement
if(i == n)<br />
that statement will never be true as you start you by ensuring i < n in the statement if (i < n)

4) I can go on a bit here, but I'm not even sure you understand what I've just written, and I really don't want to write 2-3 pages here if you can't use i for anything, your question is simply to large. And from the bottom of my heart I highly suggest you do not use WPF untill you have a good crasp of C#.

But if you have a specific question about your code feel free to ask and I'll attempt to explain it for you.



Ok, if I understand correctly, your problem is now that you have an instance in window1 which you would like to use in window2.

You can solve this in a couple of ways:
1) You can make the carlist field public and static e.g. public static List<car> carlist = new List<car>();</car></car> when you do that you can access it like so window1.carlist here window1 is not an instance but the type/class name.
This is not a very good solution, fields shouldn't be public and if you have two instances of window1 then they would share the carlist
2) You can give window2 an the instance of window1 you're using, and make the carlist field public or make a property that return the carlist.
3) You can give the carlist to window2 by passing it to the constructor. This is what I would suggest you do.
E.g.
C#
public partial class window1 : Window
{
...
    private void button2_Click(object sender, RoutedEventArgs e)
    {
        window2 win2 = new window2(carlist);
        win2.Show();
    }
...
}

C#
public partial class window2 : Window
{
    private IList<car> carlist;
...
    public window2(IList<car> carlist)
    {
        this.carlist = carlist; // this is the reference to the current instance so
                                // this.carlist refers to the field carlist not the parameter.
        InitializeComponent();
    }
...
}
 
Share this answer
 
v4
Comments
steersteer 9-Sep-11 10:50am    
Thanks. I am interested in graphics and stuff. Especially Like creating animations and games. Thought I could learn a bit of this and that at the same time, but will definitely work on C# strongly.
Simon Bang Terkildsen 9-Sep-11 11:13am    
Yeah I get you, I think you'll learn faster if you go with one thing at a time though. Back in the 90s when I started leaning, I did exactly what you seem to be doing, and I thought I were good after a year because I could make all these cool things. But what I didn't realize was I didn't really understand what I was doing, so when I tried to do something I couldn't find examples for I were at a loss, not able to solve a problem myself.
So for example I suggest you should be able to answer questions like those below, before starting to play around with WPF, databases ect.
what is:
- a class
- an instance
- a constructor
- a default contractor
- inheritance
- polymorphism
- a value type
- a reference type
- the Stack
- the Heap
steersteer 9-Sep-11 11:26am    
Thanks fore the reply. I have basic knowledge about classes, objects and constructors., but have not tried inheritance and polymorphism. know a little bit about parameter types but nothing about stack and heap. :). I have updated my question above. could you please take a look at it and let me know if anything could be done to get the desired output ? I would like to use the window1's carlist in window2 too, or copy the window1's list contents into a new list in window2. Thanks
Simon Bang Terkildsen 9-Sep-11 11:48am    
Stack and Heap are not that important, for the casual developer they are not worth spending much time on, just spend 15 mins to look them up have see what they are about.
I've updated my answer in response to your updated question.
steersteer 9-Sep-11 12:22pm    
will do. I am thinking of buying a good book about c# or .NET(latest one), if it comes under my budget. I got used to the habit of reading from books, and I find it a bit difficult reading technical material from computer screen. Anyway, thanks for the answer again. I tried your first way. I get an error "inconsistent accessibility". now working on passing parameters through constructors. I have successfully passed the value "n" from window1 to window2 through the constructor of window2, but passing the list bugs me a little. same error as before i guess. Btw, any thought about creating the objects(newcars) based on the value given by user "n"(number of cars)
I think your "fully lubed" in great advice here :), but let me add a few comments, at the risk of oil-pan overflow:

0. what seems 'missing' in the structure of your list is some ID for each Car: what if you have four cars that all have the same identical specs ?

1. replace the TextBoxes used to enter values for Number of Cars, Cylinders, HorsePower, etc., with NumericUpDown controls. (I assume that WPF offers them, or an equivalent ?).

2. consider encapsulating all your business with 'Car' objects in a class (and/or NameSpace as shown here), perhaps like this:
C#
using System.Collections.Generic;

namespace Cars
{
    public class Car
    {
        public double Cylinders{get; set;}

        public double Topspeed{get; set;}

        public double Horsepower{get; set;}
    }

    // we're using inheritance here to make a List<Car>
    public class CarList: List<Car>
    {
        private static int defaultCylinders = 8;
        private static double defaultTopSpeed = 100.0;
        private static double defaultHorsePower = 90.0;

        // we are overloading the Add operator here
        // to allow us to check for the need to set
        // default values, if they are missing ...
        internal void Add(Car newCar)
        {
            if (newCar.Cylinders == 0.0) newCar.Cylinders = defaultCylinders;
            if (newCar.Horsepower == 0.0) newCar.Horsepower = defaultHorsePower;
            if (newCar.Topspeed == 0.0) newCar.Topspeed = defaultTopSpeed;

            // here we call the underlying List<Car> 'Add method
            base.Add(newCar);
        }
    }
}
If there's going to be one-and-only-one List of Cars, you can make the 'CarList class static.

So how would you use this style Class definition to actually make the List: assume this code is in some window or context separate from the (NameSpace of and) definition of the 'Cars' class:
// expose a Public Property containing the CarList built
// in this Window or Context
// so other Windows or Contexts can use it
public Cars.CarList TheCarList { set; get; }

// button press that triggers making the list of cars
private void MakeCarList_Click(object sender, EventArgs e)
{
    // the list of cars to be built
    var ListOCars = new Cars.CarList();

    // 'seed' the exposed public property
    TheCarList = ListOCars;

    int nCars = (int) numericUpDown1.Value;

    for (int i = 0; i < nCars; i++)
    {
        var NewCar = new Cars.Car
        {
            TopSpeed = (double) numericUpDown2.Value,
            Cylinders = (double) numericUpDown3.Value,
            HorsePower = (double) numericUpDown4.Value
        };

        ListOCars.Add(NewCar);
    }
}

The above example uses techniques, syntax (var), and object-initializer syntax, from C#2.0, and later. Tested and verified in WinForms only.
 
Share this answer
 
v4
Comments
steersteer 9-Sep-11 13:50pm    
Thanks. will try and implement this technique now..

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