How do I use collected data from program? - c#

I have a program that is suppose to collect user car data in one method/class and then use it later.
In this case, user types in Year: 2001 Make: Mustang Model: GT (click Make the Car Button). The textboxes are cleared. Then click accelerate. In the DetailLabel it should increment speed by 5 every time the button is pressed. Output: The speed of 2001 Mustang GT is 5 mph. Same for the Brake Button. The speed of 2001 Mustang GT is 0 mph.
Problem: I can't access/use my collected data for brake or accelerate buttons.
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarMaker_Tate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetCarData()
{
CarClass myCar = new CarClass();
int CYear;
string CMake = MakeTextBox.Text;
String CModel = ModelTextBox.Text;
if (int.TryParse(YearTextBox.Text, out CYear) && CYear >= 1900 && CYear <= 2022)
{
if (CMake != "")
{
if (CModel != "")
{
myCar.Year = CYear;
myCar.Make = CMake;
myCar.Model = CModel;
}
else
MessageBox.Show("Please enter a car model");
}
else
MessageBox.Show("Please enter a car make");
}
else
MessageBox.Show("Please enter a year between 1900 - 2022");
}
private void MakeButton_Click(object sender, EventArgs e)
{
GetCarData();
YearTextBox.Text = "";
MakeTextBox.Text = "";
ModelTextBox.Text = "";
}
private void AccelerateButton_Click(object sender, EventArgs e)
{
myCar.AccSpeed(5);
DetailLabel.Text = "The speed of " + myCar.Year + myCar.Make + myCar.Model + "is" + myCar.Speed + "mph";
}
private void Summarybutton_Click(object sender, EventArgs e)
{
Summary mySummaryForm = new Summary();
mySummaryForm.Show();
}
private void BrakeButton_Click(object sender, EventArgs e)
{
myCar.DecSpeed(5);
DetailLabel.Text = "The speed of " + myCar.Year + myCar.Make + myCar.Model + "is" + myCar.Speed + "mph";
}
}
}
CarClass.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarMaker_Tate
{
class CarClass
{
int CarYear;
string CarMake;
string CarModel;
public static int CarCount;
public CarClass()
{
// constructor runs everytime a car is created
CarYear = 0;
CarMake = "";
CarModel = "";
CarCount++;
}
public int Year
{
get
{
return CarYear;
}
set
{
CarYear = value;
}
}
public string Make
{
get { return CarMake; }
set { CarMake = value; }
}
public string Model
{
get { return CarModel; }
set { CarModel = value; }
}
public int Speed
{
get { return Speed; }
set { Speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}

You should declare myCar as a variable outside the GetCarData() method. Otherwise only the method GetCarData can access it. You can even think to make the variable static:
Like that:
public partial class Form1 : Form
{
// declare myCar for the entire class
private static CarClass myCar;
public Form1()
{
InitializeComponent();
}
private void GetCarData()
{
// init myCar
myCar = new CarClass();
...
}
}

Related

Where to create my objects in a windows form app?

I'm trying to create an object in my windows form app but if I create it in the constructor, then I can't access it in the entire app...(Like the events) In the code below the Time1 isn't available. I'll be happy to hear from you...
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClockApp
{
public partial class ClockApp : Form
{
public ClockApp()
{
InitializeComponent();
ClockApp Time1 = new ClockApp();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void ClockApp_Load(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
//ClockApp Time1 = new ClockApp();
Time1.getHour = Convert.ToInt16(txtHour.Text);
Time1.getMin = Convert.ToInt16(txtMin.Text);
Time1.getSec = Convert.ToInt16(txtSec.Text);
if(rbUniversal.Checked == true)
{
Time1.ToUniversal();
}else if(rbStandard.Checked == true)
{
Time1.ToStandard();
}
else
{
lblTime.Text = "NOT Working...";
}
}
}
}
The code below is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClockApp
{
public partial class ClockApp : Form
{
// Fields
private int Hour;
private int Min;
private int Sec;
// Properties
public int getHour
{
get
{
return Hour;
}
set
{
if(value > 23 && value < 0)
{
Hour = 23;
}
else
{
Hour = value;
}
}
}
public int getMin
{
get
{
return Min;
}
set
{
if(value > 59 && value < 0)
{
Min = 59;
}
else
{
Min = value;
}
}
}
public int getSec
{
get
{
return Sec;
}
set
{
if(value > 59 && value < 0)
{
Sec = 59;
}
else
{
Sec = value;
}
}
}
// Constructors
// Methods
// ToUniversal()
public void ToUniversal()
{
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
// ToStandard()
public void ToStandard()
{
if(Hour > 12)
{
int[] Modifier = new int[12];
for (int i = 0; i < 12; i++)
{
Modifier[i] = i + 13;
if (Hour == Modifier[i])
{
Hour = i+1;
lblAMPM.Text = "PM";
}
}
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
else
{
lblAMPM.Text = "AM";
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
}
}
}
You dont need to create a new instance of ClockApp in the constructor.
Remove that line.
The field (or whatever) 'Time1' is not needed. Remove 'Time1.' completely form your code:
Time1.getHour = Convert.ToInt16(txtHour.Text); => getHour = Convert.ToInt16(txtHour.Text);
Time1.ToUniversal(); => ToUniversal();
and so on.
That should make your code at least compilable.
Bugs:
value > 23 && value < 0 is always false. You have to use || instead of &&.
same for value > 59 && value < 0
Code conventions:
I know you just starting with c#, but please check the common coding convention to improve the readabilty:
Properties: first letter is capitalized
Fiels: first letter is not capitalized
Do not start you propery name with 'get'. Just Hour, Min or Sec is perfect.

String building and form component access from class

Background
I am writing a program, which collects different events (key press, mouse position, and others) and sends a single string to a serial port.
There is a small part of the program, where a key is pressed, to control movement (forward - W key; left - A key, Forward-left - WA key).
When an event happens, a method is invoked, which grabs a numeric string and processes in the FinalStringClass Class. On the main form , there is a method, which assigns collected value to a label.
However, I am encountering a problem with code due to lack of experience in programming :(
Main Form:
Serial port;
FinalStringClass fstr;
public Form1()
{
InitializeComponent();
//... Serial port settings
timer.Start();
fstr = new FinalStringClass(UpdateLabel2);
}
public void UpdateLabel2(string x, string y, string speed, string mvm) //
{
label2.Text = "x: " + x + "y: " + y + "speed: " + speed + "mvm: " + mvm;
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
if (left.IsPressed)
{
if (up.IsPressed == true) // if W and A keys are pressed, ->
{
fstr.mvmMethod("7"); // this method is triggered
return;
}
if (down.IsPressed)
{
fstr.mvmMethod("9");
return;
}
if (right.IsPressed)
{
fstr.mvmMethod("1");
return;
}
fstr.mvmMethod("4"); //if W key is pressed, then this method is triggered
}
//... (other if condition statements)
label2.Text = fstr.FinalStringBuilder();
port.Write(fstr.FinalStringBuilder());
}
External Class:
class FinalStringClass
{
private Action<string, string, string, string> updateLabel2;
Action<String> _x, _y, _speed, _mvm;
string xF, yF, speedF, mvmF;
public FinalStringClass(Action<string, string, string, string> updateLabel2)
{
this.updateLabel2 = updateLabel2;
}
public FinalStringClass(Action<String> x, Action<String> y, Action<String> speed, Action<String> mvm)
{
_x = x;
_y = y;
_speed = speed;
_mvm = mvm;
}
public void xMethod(string x)
{
_x(x);
xF = x;
}
public void yMethod(string y)
{
_y(y);
yF = y;
}
public void speedMethod(string speed)
{
_speed(speed);
speedF = speed;
}
public void mvmMethod(string mvm)
{
_mvm(mvm);
mvmF = mvm;
}
public string FinalStringBuilder()
{
return xF + yF + speedF + mvmF;
}
}
When working with a single parameter, everything works fine. But dealing with multiple parameters causes a problem :(
Example of working with a single parameter (full working code):
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FFApp
{
public partial class Form1 : Form
{
SerialPort port;
MyClass outside;
public Form1()
{
InitializeComponent();
timer.Start();
outside = new MyClass(UpdateLabel);
}
public void UpdateLabel(string str)
{
label1.Text = str;
}
private void init()
{
port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 115200;
try
{
port.Open();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
public struct KeyStateInfo
{
private Keys key;
private bool isPressed;
private bool isToggled;
public KeyStateInfo(Keys key, bool ispressed, bool istoggled)
{
this.key = key;
isPressed = ispressed;
isToggled = istoggled;
}
public static KeyStateInfo Default
{
get
{
return new KeyStateInfo(Keys.None, false, false);
}
}
public Keys Key
{
get { return key; }
}
public bool IsPressed
{
get { return isPressed; }
}
public bool IsToggled
{
get { return isToggled; }
}
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
Keyboard kb = new Keyboard();
if (left.IsPressed)
{
if (up.IsPressed == true)
{
outside.MyMethod("7");
return;
}
if (down.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("4");
}
if (right.IsPressed)
{
if (up.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("8");
return;
}
if (left.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("5");
}
if (up.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("7");
return;
}
if (right.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("2");
}
if (down.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("8");
return;
}
if (up.IsPressed)
{
outside.MyMethod("9");
return;
}
outside.MyMethod("3");
}
if (!right.IsPressed && !left.IsPressed && !up.IsPressed && !down.IsPressed)
{
outside.MyMethod("1");
}
}
public class KeyboardInfo
{
[DllImport("user32")]
private static extern short GetKeyState(int vKey);
private KeyboardInfo()
{
}
public static KeyStateInfo GetKeyState(Keys key)
{
short keyState = GetKeyState((int)key);
int low = Low(keyState), high = High(keyState);
bool toggled = low == 1;
bool pressed = high == 1;
return new KeyStateInfo(key, pressed, toggled);
}
private static int High(int keyState)
{
return keyState > 0 ? keyState >> 0x10
: (keyState >> 0x10) & 0x1;
}
private static int Low(int keyState)
{
return keyState & 0xffff;
}
}
}
}
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FFApp
{
class MyClass
{
Action<String> labelSetter;
public MyClass(Action<String> labelSetter)
{
this.labelSetter = labelSetter;
}
public string MyProperty { get; set; }
public void MyMethod(string text)
{
labelSetter(text);
MyProperty = text;
}
}
}
Or is it possible within this code, to get changing values (store in a variable), when pressed W/A/D/S/W+A/W+D etc keys in order to allow building final string? ex: string finalstring = x + y + speed + pressed_key;

Property or indexer must have at least one accessor

I'm learning C#, trying to get to grips with accessors at the moment.
I'm going nuts looking at this, I have no idea what I've done wrong:
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
The Form looks like this:
public partial class BankForm : Form
{
private BankAccount _myAccount;
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
But I get this error:
Property or indexer must have at least one accessor
I'm not getting any errors. Move location of private BankAccount _myAccount;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BankForm
{
public partial class BankForm : Form
{
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private BankAccount _myAccount;
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
}
​

Using a Class with a Form

I am getting an error on lines 44 and 50.
It says:
No overload for method 'GetCarData' takes 1 arguments
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere.
Any and all help is much appreciated. I have never worked with classes before.
Here is the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData()
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
If the error says
No overload for method 'GetCarData' takes 1 arguments
then look at the calls you make to GetCarData and check that they don't try to pass a parameter (argument) to it. It's declared as
private void GetCarData()
which is good, and the two calls (lines 44 and 50) are consistent with that:
GetCarData();
so make sure that the code on your computer matches what's here, save it, and re-compile.

Creating a Car Class that Incorporates Speed, Model, and Make

I am getting a new error after having added the () to the Car instantiation.
It says:
'Car_Class_BBrantley.Form1.myCar()' must declare a body because it is not marked abstract, extern, or partial
The error is thrown on line 14.
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
Here is the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar();
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData(Car car)
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
Change
private Car myCar();
to
private Car myCar;
and
private void GetCarData(Car car)
to
private void GetCarData()
change
myCar = new Car;
to myCar = new Car();

Categories

Resources