Wednesday, April 30, 2014
Create List Of Objects
namespace Create_List_Of_Objects
{
public partial class Form1 : Form
{
List<Car> carList = new List<Car>();
public Form1()
{
InitializeComponent();
}
private void btnCreateCar_Click(object sender, EventArgs e)
{
try
{
//get user input
string make = txtMake.Text;
string model = txtModel.Text;
int mileage = int.Parse(txtMileage.Text);
decimal price = decimal.Parse(txtPrice.Text);
//use the data to create a Car object
Car car = new Car(make, model, mileage, price);
//save it to the list
carList.Add(car);
//
System.Media.SystemSounds.Beep.Play();
}
catch (FormatException fe)
{
MessageBox.Show(fe.Message, "Format Exception",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Preload few cars to the list
Car car = new Car("Honda", "Civid", 1200, 18000);
carList.Add(car);
car = new Car("Toyota", "Prius", 15000, 8600);
carList.Add(car);
car = new Car("Ford", "F-150", 45000, 9780);
carList.Add(car);
car = new Car("Subaru", "Forester", 135000, 3500);
carList.Add(car);
car = new Car("Ford", "Focus", 95000, 2500);
carList.Add(car);
}
private void btnDisplayCars_Click(object sender, EventArgs e)
{
DisplayCars();
}
private void DisplayCars()
{
richTextBox1.Clear();
foreach (Car car in carList)
{
richTextBox1.AppendText(String.Format
("{0, -10} {1, -9} {2, -15} {3:c} \n",
car.Make, car.Model, car.Mileage, car.Price));
}
}
}
public class Car
{
//private fields
private string _make;
private string _model;
private int _mileage;
private decimal _price;
//constructor
public Car(string make, string model, int mileage, decimal price)
{
_make = make;
_model = model;
_mileage = mileage;
_price = price;
}
public string Make
{ get { return _make; } }
public string Model
{ get { return _model; } }
public int Mileage
{ get { return _mileage; } }
public decimal Price
{ get { return _price; } }
}
}
//Define a class Account
//fields: _accountNumber, _balance, _bankName, _interestRate
//Add constructor + properties
//===============================
//In Form1: Create GUI to add new Account to a List
//-Preload List with few Accounts
//-Display entire list
Labels:
C#
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment