how can I add items to my ListView - c#

I keep getting this error and I know why but I need help figuring out how I can solve it. The only way I have been able to add my items it to make a new form but that seems silly.
It wont work if I make all my methods static =(
I keep getting,
"An object reference is required for the non-static field, method, or
property 'Handicap_Calculator.FormMain.listViewLog'
\Form1.cs 74 13 Handicap Calculator"
Here´s my code:
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 Handicap_Calculator
{
public partial class FormMain : Form
{
//FormAddScore FormAddNewScore = new FormAddScore();
public static bool addScoreIsShown = false;
public static FormAddScore _FormAddScore;
public static ListViewItem Item;
//public static List<string> ScoreInfo = new List<string>();
public FormMain()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
try
{
if (_FormAddScore == null || _FormAddScore.IsDisposed)
{
_FormAddScore = new FormAddScore();
}
_FormAddScore.Show();
if (_FormAddScore.WindowState == FormWindowState.Minimized)
{
_FormAddScore.WindowState = FormWindowState.Normal;
}
_FormAddScore.BringToFront();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static void AddScore()
{
int Round = 1;
DateTime date = _FormAddScore.date;
string course = _FormAddScore.course;
int holes = _FormAddScore.holes;
int score = _FormAddScore.score;
float courseRating = _FormAddScore.courseRating;
float slopeRating = _FormAddScore.slopeRating;
string[] ScoreInfo = new string[7];
ScoreInfo[0] = Round.ToString();
ScoreInfo[1] = date.ToString();
ScoreInfo[2] = course;
ScoreInfo[3] = holes.ToString();
ScoreInfo[4] = score.ToString();
ScoreInfo[5] = courseRating.ToString();
ScoreInfo[6] = slopeRating.ToString();
AddToList(ScoreInfo);
}
public static void AddToList(string[] ScoreInfo)
{
Item = new ListViewItem(ScoreInfo);
//listViewLog.Items.Add(Item);
}
}
}
Edit...
Here is the class im calling it from:
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 Handicap_Calculator
{
public partial class FormAddScore : Form
{
public DateTime date;
public string course;
public int holes;
public int score;
public float courseRating;
public float slopeRating;
public FormAddScore()
{
InitializeComponent();
}
private void FormAddScore_FormClosing(object sender, FormClosingEventArgs e)
{
FormMain.addScoreIsShown = false;
}
public void getscore()
{
try
{
date = dateTimePicker1.Value;
course = textBoxCourse.Text;
holes = Convert.ToInt16(textBoxHoles.Text);
score = Convert.ToInt16(textBoxScore.Text);
courseRating = Convert.ToSingle(textBoxCourseRating.Text);
slopeRating = Convert.ToSingle(textBoxSlopeRating.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
getscore();
FormMain.AddScore();
}
}
}

The simple solution is to define your methods AddScore and AddToList as non-static.
public void AddScore()
{
//your code
}
public void AddToList(string[] ScoreInfo)
{
// your code
}
If you want to use static methods you should pass the instance of your Form to the method, on which you want to add items to the ListView.
public static void AddScore(FormMain mainForm)
{
//your code
AddToList(mainForm, ScoreInfo);
}
public static void AddToList(FormMain mainForm, string[] ScoreInfo)
{
// your code
}
Update:
According to your updated code the solution is to pass the instance of your FormMain to your FormAddScore when you create it. In FormAddScore you store the reference to the FormMain instance to call the methods on.
public partial class FormAddScore : Form
{
// your code
private FormMain _mainForm;
public FormAddScore(){
InitializeComponent();
}
public FormAddScore(FormMain mainForm) : this(){
_mainForm = mainForm;
}
In your FormMain when you create the instance of FormAddScore you should use the constructor that expects an instance of FormMain
_FormAddScore = new FormAddScore(this);
With this setup you can change your methods to non-static and you can call the methods of FormMain in your FormAddScore, by using the stored reference in variable _mainForm.
_mainForm.AddScore();

Related

Running a Method from SoundEngine class's object anywhere

I am struggeling with getting my SoundEngine class's function PlaySound to be played where I want it.
The function needs to be a global function but I can't make it static as the function refers to an object that the SoundEngine makes.
I'll show the snippets that are important:
In my GameWorld class:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input;
using System;
using SoundEngineSpace;
public GameWorld(int width, int height, ContentManager Content)
{
screenWidth = width;
screenHeight = height;
random = new Random();
gameState = GameState.Playing;
block = Content.Load<Texture2D>("block");
font = Content.Load<SpriteFont>("SpelFont");
SoundEffect blockFallSE = Content.Load<SoundEffect>("BlockFallSE");
Song BuildingWallsintheCold = Content.Load<Song>("91 Building Walls in the Cold");
soundEngine = new SoundEngine();
soundEngine.addSound(blockFallSE);
soundEngine.addSong(BuildingWallsintheCold);
soundEngine.SetSoundVolume(20);
soundEngine.SetSongVolume(5);
soundEngine.PlaySong(0);
grid = new TetrisGrid(block);
}
In my TetrisGrid class
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SoundEngineSpace;
...
public void TetNaarBeneden()
{
soundEngine.PlaySound(0);
InPlayGrid.Velocity = new Vector2(0, gridblock.Height);
CheckValidLocation();
}//Moves tet down
And the soundEngine class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
namespace SoundEngineSpace
{
public class SoundEngine
{
private void soundEngine()
{
}
BackgroundSound backgroundSound = new BackgroundSound();
SoundEffects soundEffects = new SoundEffects();
public void addSong(Song s)
{
backgroundSound.AddBackgroundSound(s);
}
public void addSound(SoundEffect s)
{
soundEffects.AddSound(s);
}
public void PlaySong(int s)
{
backgroundSound.PlayBackgroundSound(s);
}
public void PlaySound(int s)
{
soundEffects.PlaySound(s);
}
public void SetSongVolume(int v)
{
backgroundSound.SetBackGroundSoundVolume(v);
}
public void SetSoundVolume(int v)
{
soundEffects.SetSoundEffectVolume(v);
}
}
}
class BackgroundSound
{
public static void backGroundSound()
{
}
private List<Song> BackgroundSoundEffects = new List<Song>();
private bool PlayingBackGroundSound = false;
public void AddBackgroundSound(Song s)//addsongs to the list
{
BackgroundSoundEffects.Add(s);
}
public void PlayBackgroundSound(int s)//plays BackgroundSound based on location in the list
{
MediaPlayer.IsRepeating = true;//If I use this exact soundengine again, move this to it's own function instead!
if (BackgroundSoundEffects.Count() > s)
{
if (PlayingBackGroundSound)
MediaPlayer.Stop();
MediaPlayer.Play(BackgroundSoundEffects.ElementAt(s));
PlayingBackGroundSound = true;
}
else
{
Console.WriteLine("Couldent find the BackgroundSound");
}
}
public void SetBackGroundSoundVolume(int v)
{
MediaPlayer.Volume = (float)v/100;
}
}
class SoundEffects
{
public static void soundeffects()
{
}
private List<SoundEffect> soundEffects = new List<SoundEffect>();
public void AddSound(SoundEffect s)//addsongs to the list
{
soundEffects.Add(s);
}
public void PlaySound(int s)//plays sound based on location in the list
{
if (soundEffects.Count() > s)
{
SoundEffect ToPlaySound = soundEffects.ElementAt(s);
ToPlaySound.Play();
}
else
{
Console.WriteLine("Couldent find the sound");
}
}
public void SetSoundEffectVolume(int v)
{
SoundEffect.MasterVolume = (float)v/100;
}
}
I ended up making the constructor of objects that needed acces to the SounEngine pass the SoundEngine as a paramter.
Then I could create a new soundEngine within the object I needed it to exsist and call: this.soundEngine = soundEngine.
That succesfully copied the soundEngine and let me use it's fucntions.

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

Updating a Control Within a Currently Open Form

I am writing a C# Application where I can add various types of students - a normal student, or a academic society student, or a arts and culture society student. On the main form, I have 3 data grids (one lists academic students, one list arts and culture students, and the other lists the normal students). For the user to specify additional information about a student (should they be an academic society student, or an arts and culture student, or both), another form will open up asking the user to add additional Information.
After the information has been specified, I would like to take that information, and add it to the relevant data grid, in other words, update the data grid in the main form.
How I thought I would tackle this idea:
Create a method in the main form to add a new entry to the data grid
Save the main form object into a Form object
Have a method which will will add a new row of data into the form object mentioned in step 2
Update the currently open main form with the form object I had saved.
I tried doing the above, and I get the error:
Error 1 Inconsistent accessibility: parameter type 'ONT2000_Practical_05.AcademicSocieties' is less accessible than method 'ONT2000_Practical_05.Form1.addAcademicStudentRow(ONT2000_Practical_05.AcademicSocieties)' c:\users\okuhle\documents\visual studio 2013\Projects\ONT2000 Practical 05\ONT2000 Practical 05\Form1.cs 35 21 ONT2000 Practical 05
I have 3 classes - AcademicSocieties, ArtsAndCultureSociety and Student...both AcademicSocieties and ArtsAndCultureSociety inherit the Student class. Below is the code for the classes:
THE STUDENT CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class Student
{
private String studentNumber;
private String studentName;
private String studentDegree;
public Student(string number, string name, string degree)
{
studentNumber = number;
studentName = name;
studentDegree = degree;
}
public String getStudentName()
{
return studentName;
}
public String getStudentNumber()
{
return studentNumber;
}
public String getStudentDegree()
{
return studentDegree;
}
}
}
THE ACADEMICSSOCIETY CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class AcademicSocieties : Student
{
private String courseCode;
private String societyName;
public AcademicSocieties(String studentName, String studentNumber, String studentDegree, String courseCode, String societyName) : base(studentNumber, studentName, studentDegree)
{
this.courseCode = courseCode;
this.societyName = societyName;
}
public String getCourseCode()
{
return courseCode;
}
public String getSocietyName()
{
return societyName;
}
}
}
THE ARTSANDCULTURE SOCIETY CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
class ArtsAndCultureSociety : Student
{
private int experienceLevel;
private int competitionWins;
private String societyName;
private Boolean colours;
public ArtsAndCultureSociety(int level, int wins, string societyName, String studentNumber, String studentName, String studentDegree) : base(studentNumber, studentName, studentDegree)
{
experienceLevel = level;
competitionWins = wins;
this.societyName = societyName;
}
}
}
THE MAIN FORM:
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 ONT2000_Practical_05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void academicSocietiesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void degreeLabel_Click(object sender, EventArgs e)
{
}
private void exitApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
public void addAcademicStudentRow(AcademicSocieties thisStudent) //This is where the Error Occurs
{
academicSocietiesDataGrid.Rows.Add(thisStudent.getStudentName(), thisStudent.getSocietyName(), thisStudent.getCourseCode());
}
private void addStudentButton_Click(object sender, EventArgs e)
{
String studentName = ProgramFunctions.validateTextBoxData(studentNameTextBox);
String studentNumber = ProgramFunctions.validateStudentNumber(studentNumberTextBox);
String studentDegree = ProgramFunctions.validateTextBoxData(degreeTextBox);
if (studentName.Equals(null) || studentNumber.Equals(null) || studentDegree.Equals(null) || studentDegree.Equals("null")) //Error 1 is on this line
{
ProgramFunctions.displayMessage("Data Integrity Error", "As a result of one or more fields failing data validation, this application will not continue processing data");
} else
{
if (artsAndCultureCheckBox.Checked && academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
GeneralStudentSocietyForm generalForm = new GeneralStudentSocietyForm();
generalForm.Visible = true;
generalForm.Focus();
} else if (academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
AcademicSocietyForm academics = new AcademicSocietyForm();
academics.Visible = true;
academics.Focus();
} else if (artsAndCultureCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
ArtsAndCultureForm artsAndCulture = new ArtsAndCultureForm();
artsAndCulture.Visible = true;
artsAndCulture.Focus();
} else
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.addNewStudent(newStudent);
ProgramFunctions.displayMessage("Student Added", "A New Student has successfully been added to the database. Click OK to continue");
studentDataDataGird.Rows.Add(newStudent.getStudentName(), newStudent.getStudentNumber(), newStudent.getStudentDegree());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
ProgramFunctions.addNewAcademicSociety("Accounting Society");
ProgramFunctions.addNewAcademicSociety("Law Student Society");
ProgramFunctions.addNewAcademicSociety("Science Student Society");
ProgramFunctions.addNewAcademicSociety("Information Technology Student Society");
ProgramFunctions.addNewAcademicSociety("Business Science Student Society");
ProgramFunctions.addNewArtsAndCultureSociety("Choir Society");
ProgramFunctions.addNewArtsAndCultureSociety("Hip Hop Society");
ProgramFunctions.addNewArtsAndCultureSociety("Anime Society");
ProgramFunctions.addNewArtsAndCultureSociety("The Hockey Society");
}
private void studentDataDataGird_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void academicSocietiesDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
THE PROGRAMFUNCTIONS Class (This is where I am saving the Form Object):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ONT2000_Practical_05
{
class ProgramFunctions
{
private static List<String> academicSocieties = new List<String>();
private static List<String> artsAndCultureSocieties = new List<String>();
private static Form1 formObject;
public static void saveCurrentForm(Form1 formData)
{
formObject = formData;
}
public static void academicStudentDataGridRow(AcademicSocieties newStudent)
{
formObject.addAcademicStudentRow(newStudent);
}
public static Form1 updateMainForm()
{
return formObject;
}
public static void addNewAcademicSociety(String societyName)
{
academicSocieties.Add(societyName);
}
public static void addNewArtsAndCultureSociety(String societyName)
{
artsAndCultureSocieties.Add(societyName);
}
public static void displayMessage(String title, String Message)
{
MessageBox.Show(Message, title);
}
public static String validateTextBoxData(TextBox thisTextBox)
{
if (thisTextBox.Text.Equals(null) || thisTextBox.Text.Equals("") || thisTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You may not specify empty data for the student");
return null;
} else
{
thisTextBox.Text = thisTextBox.Text.Trim();
thisTextBox.Text = thisTextBox.Text.ToUpper();
return thisTextBox.Text;
}
}
public static String getSelectedItem(ComboBox thisComboBox)
{
return thisComboBox.SelectedItem.ToString();
}
public static int getArtsAndCultureCount()
{
return artsAndCultureSocieties.Count;
}
public static int getAcademicSocietyCount()
{
return academicSocieties.Count;
}
public static String getAcademicSociety(int index)
{
return academicSocieties[index];
}
public static String getArtsAndCultureSociety(int index)
{
return artsAndCultureSocieties[index];
}
public static String validateStudentNumber(TextBox studentNumberTextBox)
{
if (studentNumberTextBox.Text.Equals(null) || studentNumberTextBox.Text.Equals("") || studentNumberTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You did not input any data...Please be sure you do specify some data");
return null;
} else
{
if (!studentNumberTextBox.Text.StartsWith("s"))
{
displayMessage("Invalid Student Number", "You have entered an invalid student number. Please be sure this student number follows the correct format. The student number must begin with a 's' character. ");
return null;
}
if (studentNumberTextBox.Text.Length != 10)
{
displayMessage("Invalid Student Number", "The student number specified may not be longer than 10 characters");
return null;
}
return studentNumberTextBox.Text;
}
}
}
}
change the access modifier of the class ProgramFunctions,ArtsAndCultureSociety to public.
Could it be you are missing the access modifier 'public' in some of your class definitions? If you don't add public before ArtsAndCultureSociety, it will be private.

How do i pass variables from class to a new class?

I have this class wich I will make an instance for it in Form1 later that pass variables from Form1 to the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GatherLinks
{
class WebcrawlerConfiguration
{
public string url;
public int levels;
public string mainurl;
public Dictionary<string,List<string>> localy;
public bool removeext;
public bool downloadcontent;
public int failedUrls;
public bool toCancel;
public System.Threading.ManualResetEvent busy;
public WebcrawlerConfiguration()
{
}
}
}
How do I make that this class will get the variables from Form1 ?
Each variable in the class should get the variable in Form1 when I will make an instance for the class.
Then I have this class:
class BackgroundWebCrawling
{
int counter = 0;
List<string> WebSitesToCrawl;
BackgroundWorker mainBackGroundWorker;
BackgroundWorker secondryBackGroundWorker;
WebCrawler webcrawler1;
WebcrawlerConfiguration webcrawlerCFG;
public BackgroundWebCrawling()
{
mainBackGroundWorker = new BackgroundWorker();
mainBackGroundWorker.DoWork += mainBackGroundWorker_DoWork;
}
private void mainBackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < WebSitesToCrawl.Count; i++)
{
if (counter >= 3)
{
Thread.Sleep(10);
}
else
{
webcrawler1 = new WebCrawler(webcrawlerCFG);
counter++;
secondryBackGroundWorker = new BackgroundWorker();
secondryBackGroundWorker.DoWork += secondryBackGroundWorker_DoWork;
}
}
}
private void secondryBackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (offlineOnline == true)
{
offlinecrawling(f, levelsToCrawl, e);
}
else
{
webcrawler1.webCrawler(
}
counter--;
}
In the bottom here im doing: webcrawler1.webCrawler(
The function webCralwer should get all the variables from the first class WebcrawlerConfiguration.
This is how the WebCrawler function looks like:
public List<string> offlinecrawling(string url, int levels, string mainurl, Dictionary<string, List<string>> localy, bool removeext, bool downloadcontent, int failedUrls, bool toCancel, System.Threading.ManualResetEvent busy)
So now when im doing webcrawler1.webCrawler(
It's asking for all the variables...But I want to pass them somehow from the WebcrawlerConfiguration.
How can I do it ?

Noob Concern: Assigning a value to variable from new class object. C#

DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
I am creating a new object of the DinnerFun class and trying to assign the value from the numeric up down object from the form to the int variable PeepQty.
When I go into debug mode, I can see that sure enough nudPeepQty has a numeric value, but it is never assigned to PeepQty, and my ending calculation always ends as 0.
As the problem might be something related to something I've done outside this line of code, I will add the rest of my project below:
DinnerParty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MonuEventPlanning
{
class DinnerFun
{
const int FoodCost = 25;
public int PeepQty;
decimal CostOfBeverage;
decimal CostOfDecorations;
decimal TotalCost;
public void CalcDrinks(bool HealthOption)
{
if (HealthOption)
{
CostOfBeverage = 5M;
}
else
{
CostOfBeverage = 20M;
}
}
public void CalcDecorations(bool FancyOption)
{
if (FancyOption)
{
CostOfDecorations = (PeepQty * 15M) + 50M;
}
else
{
CostOfDecorations = (PeepQty * 7.5M) + 30M;
}
}
public decimal CalcTotalCost(bool HealthyOption)
{
if (HealthyOption)
{
TotalCost = (CostOfDecorations + CostOfBeverage) * .95M;
return TotalCost;
}
else
{
TotalCost = (CostOfBeverage + CostOfDecorations) + (PeepQty*25M);
return TotalCost;
}
}
}
}
------------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.Windows.Forms;
namespace MonuEventPlanning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost();
}
public void DisplayCost()
{
DinnerFun dinnerFun = new DinnerFun();
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}
}
}
The issue is that you are creating another DinnerFun that is not the same as the first one. Naturally the DinnerFun object in DisplayCost will have zero for the property value. Perhaps you meant this...
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost(dinnerFun);
}
public void DisplayCost(DinnerFun dinnerFun)
{
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}

Categories

Resources