Rewriting my code as a Method, using C# Visual Studio - c#

I am currently having trouble understanding Methods and how they work in C#. I currently have code written for a car cost calculator program I created, I want to rearrange or break my code down using methods. I am unsure how or where to begin doing so as it pertains to my program. Here is my code, clarification would be helpful! Thank you!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//constants for the Zone entered by user
const decimal ZoneCostN = 27;
const decimal ZoneCostS = 36;
const decimal ZoneCostE = 45;
const decimal ZoneCostW = 54;
private void CalcButton_Click(object sender, EventArgs e)
{
//set the variables
decimal PackWeight = 0;
decimal CostZone = 0;
decimal CostWeight = 0;
decimal ShippingTot = 0;
decimal Net = 0;
const decimal PerPound = 18;
//parses the entry into the textboxes
decimal.TryParse(WeightText.Text, out PackWeight); ;
//algorithm for variables
CostWeight = PackWeight * PerPound;
Zonelbl.Text = "";
CostZone = 0;
//if else statement to get the zone cost
{
if (NorthButton.Checked)
{
CostZone = ZoneCostN;
}
else if (SouthButton.Checked)
{
CostZone = ZoneCostS;
}
else if (EastButton.Checked)
{
CostZone = ZoneCostE;
}
else if (WestButton.Checked)
{
CostZone = ZoneCostW;
}
else
{
MessageBox.Show("Select a zone!");
}
}
//algorithm to get total and net
ShippingTot = CostZone + CostWeight;
Net = ShippingTot / CostWeight;
//if condition for CAPPED label
if (ShippingTot >= 100)
{
CAPPEDlbl.Visible = true;
}
else
{
CAPPEDlbl.Visible = false;
}
//output for all the data
Zonelbl.Text = CostZone.ToString("c");
Weightlbl.Text = CostWeight.ToString("c");
Totallbl.Text = ShippingTot.ToString("c");
Netlbl.Text = Net.ToString("c");
}
private void ClearButton_Click(object sender, EventArgs e)
{
//clears the form
Zonelbl.Text = "";
Weightlbl.Text = "";
Totallbl.Text = "";
Netlbl.Text = "";
WeightText.Text = "";
CAPPEDlbl.Visible = false;
WeightText.Focus();
}
}

Usually, we create methods when we need to reuse a code. In your case, you should see which part of your code will be reused in the future. If it is a simple form you may don't need to change anything but imagine you want to use your clear functionality somewhere else, create a method and call it everywhere you need
void clear()
{
Zonelbl.Text = "";
Weightlbl.Text = "";
Totallbl.Text = "";
Netlbl.Text = "";
WeightText.Text = "";
CAPPEDlbl.Visible = false;
WeightText.Focus();
}
private void ClearButton_Click(object sender, EventArgs e)
{
clear();
}
Now you can reuse clear() and in case you needed to change it you only need to change the method. It's the concept and you can apply it wherever you need.

Related

Winforms Get/Set between classes causing error - Object Reference Error

Having trouble solving this one. Might just be burned out tbh, ive been at this for hours. I am new to Classes in C# and it is kicking the crap out of me trying to pass data between classes. I know there are steps that I am missing, but microsoft docs is not being very helpful with my question so here goes.
Trying to pass values from once class to another. The error code I am getting is CS0120
This is the format of what i am using within the first class
private void btn_Compute_Click(object sender, EventArgs e)
{
decimal dL = Validator(box_Left.Text);
decimal dR = Validator(box_Right.Text);
decimal Answer = 0;
string op = "";
if (rad_Add.Checked == true)
{
MathFirstClass.Left = dL;
MathFirstClass.Right = dR;
op = " + ";
}
}
and the code inside the other class that I am trying to send the data to looks like this
decimal left;
decimal right;
decimal Answer;
public decimal Left
{
get { return left; }
set { left = value; }
}
public decimal Right
{
get { return right; }
set { right = value; }
}
public decimal Add_Operands
{
get
{
Answer = Left + Right;
return Answer;
}
}
Also if anyone wants to fill me in on how to send the answer back to the first class that would also be a great help.
You create an instance of your class.
private void btn_Compute_Click(object sender, EventArgs e)
{
decimal dL = Validator(box_Left.Text);
decimal dR = Validator(box_Right.Text);
decimal Answer = 0;
string op = "";
//****************************************
MathFirstClass mathFirstClass = new MathFirstClass();
if (rad_Add.Checked == true)
{
mathFirstClass.Left = dL;
mathFirstClass.Right = dR;
op = " + ";
}
}

How to make a scoring system in c# (Converting int to string and string to bool in c#)

I am trying to make a scoring system where if the user inputs 1 into the text box it outputs 4 into the listbox and so on. i've tried using Convert.Int32 and .ToString and bool.Parse Nothing has worked so far.
private void PlaceBox_TextChanged(object sender, EventArgs e)
{
BadForm.place = Convert.ToInt32(points);
points = Convert.ToInt32(PlaceBox.Text);
bool.Parse(PlaceBox.Text = 1.ToString());
if (PlaceBox.Text = 1.ToString())
{
PlaceBox.Text = 4;
}
else if (PlaceBox.Text = 2)
{
PlaceBox.Text = 3;
}
else if (PlaceBox.Text = 3)
{
PlaceBox.Text = 2;
}
else if (PlaceBox.Text = 4)
{
PlaceBox.Text = 1;
}
else
{
MessageBox.Show("ERROR");
}
}
Thats the code it's very basic but and that's just for one form

No syntax errors, but program does not produce any results

I have to create a program for class. My applications needs to have value returning methods for OilLubeCharges(), FlushCharges(), MiscCharges(), OtherCharges(), TaxCharges(), TotalCharges().
It needs to have void methods for ClearOilLube(), ClearFlushes(), ClearMisc(), ClearOther(), ClearFees().
Currently my code has no syntax errors, however when I compile it it does not calculate anything. The calculate, clear, and exit buttons also do not work. Any assistance as to why these issues are occurring would be appreciated. Below is my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CalcButton_Click(object sender, EventArgs e)
{
OilLubeCharges();
FlushCharges();
MiscCharges();
OtherCharges();
TaxCharges();
TotalCharges();
}
private void ClearButton_Click(object sender, EventArgs e)
{
oilCheckBox.Checked = false;
lubeCheckBox.Checked = false;
radFlushBox.Checked = false;
tranFlushBox.Checked = false;
insCheckBox.Checked = false;
mufCheckBox.Checked = false;
tireCheckBox.Checked = false;
partsTextBox.Text = "";
laborTextBox.Text = "";
serLabTotalTextBox.Text = "";
partsTotalTextBox.Text = "";
taxPartsTextBox.Text = "";
totalFeesTextBox.Text = "";
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private int OilLubeCharges()
{
int total = 0;
if (oilCheckBox.Checked)
{
total += 26;
serLabTotalTextBox.Text = total.ToString("c");
}
if (lubeCheckBox.Checked)
{
total += 18;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int FlushCharges()
{
int total = 0;
if (radFlushBox.Checked)
{
total += 30;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tranFlushBox.Checked)
{
total += 80;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int MiscCharges()
{
int total = 0;
if (insCheckBox.Checked)
{
total += 15;
serLabTotalTextBox.Text = total.ToString("c");
}
if (mufCheckBox.Checked)
{
total += 100;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tireCheckBox.Checked)
{
total += 20;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int OtherCharges()
{
int total = 0;
int parts = 0;
int labor = 0;
if (int.TryParse(partsTextBox.Text, out parts))
{
partsTextBox.Text = parts.ToString("c");
total = parts;
}
if (int.TryParse(laborTextBox.Text, out labor))
{
laborTextBox.Text = labor.ToString("c");
return total;
}
else
{
return total;
}
}
private decimal TaxCharges()
{
decimal parts = 0;
decimal partsTax;
partsTax = parts * .06m;
taxPartsTextBox.Text = partsTax.ToString("c");
return partsTax;
}
private decimal TotalCharges()
{
decimal total = 0;
total = OilLubeCharges() + FlushCharges() + MiscCharges() + TaxCharges() + OtherCharges();
totalFeesTextBox.Text = total.ToString("c");
return total;
}
}
As stated in the comments above, most likely your events are not hooked up to your buttons. You can do this several ways; typically it's done in the designer.
To know for sure if this is the cause, try this:
public Form1()
{
InitializeComponent();
CalcButton.Click += CalcButton_Click;
}
Note that this assumes your button is named "CalcButton". You can see whether that's true in the designer as well.
If that works, you need to do the same with the rest of your buttons either the same way or by selecting the method in the designer for the button.

Injection of radiobuttonlist selected value into class

I want to create a webform with 4 types of phones like: LG, xiaomi, samsung and iphone. They will be in an Array and I will insert them into dynamic radiobuttonList in the page init.
Also, the user will have a textbox where he will put an amount of money he has. The user will also have a button that will calc if he have the budget for the selected phone from the list.
After the user selects the phone, write in the budget and press the button
he will get "in budget" or "not enough budget".
The class have property of the array to insert the all the array from the page init and will have 2 functions:
One function will take the budget number > will go to the 2nd function that will see the selected phone and the budget > do its calcs and return the result into the 1st func that will give the feedback.
Now where I am stuck:
if the class isnt made global - and i put it in init or in button click - it wont work, so im looking for a way to make it work but without putting it global
so far i managed to inject the selected value into a class property and than compare - but i want to know if there is a way that this can happen with array inside class property
maybe if anyone can help me out and refer me to a guide where i can learn more about this subject (how inject selected value into function of a class and etc) ill be glad! as everything i see is C# with console but i work with ASP.NET WEB APPLICATION (.netframework)
enter code here
namespace gfjsr{
public partial class WebForm1 : System.Web.UI.Page{
phone InsertUserInfo = new phone();
protected void Page_init(object sender, EventArgs e){
string[] myArr = new string[] { "samsung", "IPHONE", "XIAOMI","LG"};
RadioButtonList phoneList = new RadioButtonList();
phoneList.ID = "radioList";
for (int i = 0; i< myArr.Length; i++)
{
ListItem li = new ListItem();
li.Text = myArr[i];
li.Value = i.ToString();
phoneList.Items.Add(li);
}
Panel1.Controls.Add(phoneList);
Label budgetLb = new Label();
budgetLb.ID = "budglb";
budgetLb.Text = "write your budget";
Panel1.Controls.Add(budgetLb);
TextBox insertBudg = new TextBox();
insertBudg.ID = "budgTxt";
Panel1.Controls.Add(insertBudg);
Button myBtn = new Button();
myBtn.ID = "btn1";
myBtn.Click += new EventHandler(btn1_click);
myBtn.Text = "result";
Panel1.Controls.Add(myBtn);
Label Labelfeedback = new Label();
Labelfeedback.ID = "feedback";
Labelfeedback.Text = "";
Panel1.Controls.Add(Labelfeedback);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_click(object sender, EventArgs e)
{
InsertUserInfo.phoneChosen = ((RadioButtonList)FindControl("radioList")).SelectedItem.Text;
double UserBudget =
Convert.ToDouble(((TextBox)FindControl("budgTxt")).Text);
InsertUserInfo.BudgetYN(UserBudget);
((Label)FindControl("feedback")).Text = InsertUserInfo.feedback; }}}
namespace gfjsr{
public class phone{
private string _phoneChosen;
public string phoneChosen
{
get { return _phoneChosen; }
set { _phoneChosen = value; }
}
private string _feedback;
public string feedback
{
get { return _feedback; }
set { _feedback = value; }
}
public double Func1(string x)
{
double phonePrice = 0;
if( x == "samsung")
{
phonePrice = 4000;
}
if (x == "IPHONE")
{
phonePrice = 3500;
}
if (x == "XIAOMI")
{
phonePrice = 3000;
}
if (x == "LG")
{
phonePrice = 2000;
}
return phonePrice;
}
public void BudgetYN(double y)
{
if(y >= Func1(_phoneChosen))
{
_feedback = "positive";
}
else
{
_feedback = "no";
}
}
}
}

C# reassigning array values(down one step ex 5-4) that are within an object during a event

Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);

Categories

Resources