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

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 = " + ";
}
}

Related

Get local variable returned to another method in WinForm

So I am working on a school lab, and I am having a hell of a time with something that should be fairly basic. I have a series of buttons and 2 text-boxes. I have 1 method that all buttons go through and get passed to a new method to determine the instructions needed.
From the new method it calculates and returns the value.
Code looks like this, only using 1 button and its associated if statement in the other method.
public void PassControlDataOnClick(object sender, EventArgs e)
{
string toCall = "";
string szLeft = box_L_Input.Text;
string szRight = box_R_Input.Text;
decimal dLeft = Convert.ToDecimal(szLeft);
decimal dRight = Convert.ToDecimal(szRight);
if (sender.ToString() == "+")
{
toCall = "ADD";
}
decimal dAnswer = MathCalc(dLeft, dRight, toCall);
string szAnswer = dAnswer.ToString();
string szEquation = $"{szLeft}{" "}{((Control)sender).Text}{" "}{szRight}{" = "}{szAnswer}";
lbl_Output.Text = szEquation;
}
public decimal MathCalc(decimal dL, decimal dR, string toCall)
{
decimal dA = 0.0m;
if (toCall == "ADD")
{
dA = dL + dR;
}
return dA;
}
Every time I run this, the output I get is from the line decimal dA = 0.0m;
I need it to be the return value but for the life of me I can't figure out where I went wrong.
If you step through this code in a debugger, you will see that the if (sender.ToString() == "+") line is stepped over.
Further more, you can run sender.ToString() in the debugger's Immediate Window and see that it returns System.Windows.Forms.Button, Text: + (assuming your sender is a normal button with the text +.
In other words, this if check has no hope of ever doing what you want. Since you know the sender will be a Button, you can cast it to a Button class and get the Text value out to see if it's indeed the + button:
if (((Button)sender).Text == "+")
{
toCall = "ADD";
}

Cannot add together different variables, even though values have changed

So I'm REALLY new to coding, so I'm learning as I go. I'm doing an assignment for a course, where I have to create a party booking program for a company. The idea is simple, just selected some different options, add them up, and calculate the costs. I have labels that will change and display the integer that the variable is set to, and they work perfectly which would tell me that the variables themselves are indeed getting changed.
However, once I try to add the variables together, it doesn't work.
public partial class AdultPayment : Form
{
public static int ConvertNumberAdult = Convert.ToInt32(Adult.numberAdult);
public static int MealCost = Adult.mealPrice*ConvertNumberAdult;
private static int PrivateRoomCost;
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
public static string DisplayNumberAdult = Convert.ToString(Adult.numberAdult);
private static int CalculateWine { get; set; } = ConvertNumberAdult / 6 * 15;
public AdultPayment()
{
InitializeComponent();
lblAdultConfirmName.Text = Adult.adultContactName;
lblAdultConfirmNumber.Text = Adult.adultContactNumber;
lblAdultConfirmDate.Text = Adult.adultDate;
lblAdultConfirmTime.Text = Adult.adultTime;
lblConfirmNumberOfAdult.Text = Adult.numberAdult.ToString();
lblMealCostTotal.Text = "£"+ MealCost.ToString();
lblCostTotal.Text = "£" + TotalCost.ToString();
if (Adult.adultPrivateRoom == true)
{
PrivateRoomCost = 40;
lblAdultConfirmPrivateRoom.Text = "Yes";
lblPrivateRoomTotal.Text = "£"+ PrivateRoomCost;
}
else
{
PrivateRoomCost = 0;
lblAdultConfirmPrivateRoom.Text = "No";
lblPrivateRoomTotal.Text = "N/A";
}
if(Adult.menuOption == true)
{
lblConfirmMenu.Text = "2 Courses for £15 each";
}
if(Adult.menuOption == false)
{
lblConfirmMenu.Text = "3 Courses for £18 each";
}
if (Adult.addWine == false)
{
CalculateWine = 0;
lblConfirmWineAdded.Text = "No";
lblWineTotal.Text = "N/A";
}
else
{
lblConfirmWineAdded.Text = "Yes";
lblWineTotal.Text = "£"+ CalculateWine.ToString();
}
lblCostTotal.Text = "£" + TotalCost.ToString();
}
}
I have a different form, that allows the users to select their preferences, which works just as I need it to.
The variable that is supposed to add the other variables together is
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
I genuinely am so confused now, and because I'm so new to this I don't know how else to word it in order to find anything on the internet
Any help would be great!
Thanks!

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";
}
}
}
}

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

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.

Combobox value (binded with an enum) in an instance

Good day lads!
I've got a question.
I think I'll be saving loads of text if you would see my form, so here we go!
Form:
private void Form1_Load(object sender, EventArgs e)
{
/*
Held h1 = new Held("Tank", Lanes.Top);
Held h2 = new Held("ADC", Lanes.Bot);
Held h3 = new Held("Support", Lanes.Bot);
listBox1.Items.Add(h1);
listBox1.Items.Add(h2);
listBox1.Items.Add(h3);
*/
//Data koppelen
cbRol.DataSource = Enum.GetValues(typeof(Lanes));
}
private void btnAanmaken_Click(object sender, EventArgs e)
{
int getal;
if (CheckEmptyFields())
{
MessageBox.Show("Vul alle velden in!");
}
else
{
if (CheckMovementSpeedIsInt(out getal))
{
string naamHero = tbNaamHero.Text;
Lanes lane = ???
int mSpeedHero = getal;
Held nieuwHeld = new Held(naamHero, lane, getal);
}
}
}
private bool CheckMovementSpeedIsInt(out int getal)
{
return Int32.TryParse(tbMoveSpeed.Text, out getal);
}
private bool CheckEmptyFields()
{
return tbNaamHero.Text == null || tbMoveSpeed.Text == null || cbRol.SelectedItem == null;
}
Held:
class Held
{
private string Naam;
private Lanes Lane;
int MSpeed;
public Held(string aNaam, Lanes aLane, int aMSpeed)
{
this.Naam = aNaam;
this.Lane = aLane;
this.MSpeed = aMSpeed;
}
public override string ToString()
{
return this.Naam + " " + this.Lane.ToString();
}
}
}
Lanes:
enum Lanes
{
Top,
Mid,
Bot,
Jungle
}
Alright! So as you can see I have combined the enum with the ComboBox. I'd like to put the selected value (when the user has pressed the button "Aanmaken/Create") in the instance.
How am I able to convert the object (from ComboBox) to a type (Lanes)?
If I haven't clarified enough, just give me a heads up!
PS: The "???" in the code is the place where I'm not sure what to put since that's the question hehe.
Just use the following:
Lanes lane = (Lanes)cbRol.SelectedIndex;
This works due to enum is typeof int, so your Top is actually 0, and so on...
You can parse your Enum.Parse
Lanes lange = (Lanes) Enum.Parse(typeof(Lanes), cbRol.SelectedItem.ToString(), true);
This also works for index
Lanes lange = (Lanes) Enum.Parse(typeof(Lanes), cbRol.SelectedIndex.ToString(), true);

Categories

Resources