Validation of value in XML File - c#

I'm trying to validate a username check box to see if the value entered exists in an XML file.
On button click, it should check if the name entered exists within the XML file and then proceed, if not the message box should appear.
The current code shows that the txt_Username.Text = Pupil.forename is inaccessible due to its protection level.
On button click:
private void btnNext_Click(object sender, RoutedEventArgs e, Pupil p)
{
if (txt_Username.Text = Pupil.forename)
{
this.Hide();
Display nw = new Display(theClass);
nw.ShowDialog();
this.Show();
}
MessageBox.Show("Cannot Find username");
}
Pupil Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PassingData
{
public class Pupil
{
private string forename;
private int score;
public Pupil(string forename, int score)
{
this.forename = forename;
this.score = score;
}
public Pupil()
{
this.forename = "Unknown";
}
public string Forename
{
get { return forename; }
set { forename = value; }
}
public int Score
{
get { return score; }
set { score = value; }
}
override public string ToString()
{
string output = forename + "\t" + score;
return output;
}
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPupil xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Pupil>
<Forename>Andy</Forename>
<Score>0</Score>
</Pupil>
<Pupil>
<Forename>Bob</Forename>
<Score>10</Score>
</Pupil>
<Pupil>
<Forename>Carl</Forename>
<Score>20</Score>
</Pupil>
<Pupil>
<Forename>Dave</Forename>
<Score>30</Score>
</Pupil>
<Pupil>
<Forename>Eric</Forename>
<Score>40</Score>
</Pupil>
<Pupil>
<Forename>Frank</Forename>
<Score>50</Score>
</Pupil>
</ArrayOfPupil>

'forename' is a private variable
Pupil is not a Static Class
You need to create an instance of Pupil and use Forename property instead.
i.e
Pupil.Forename is NOT Allowed on a non-static class.
Instead
Pupil objPupil = new Pupil();
var myForeName = objPupil.Forename;
In your If statement there is only one =.
Default Button click handler/delegate cannot have the extra parameter Pupil p.

You are referencing "forename" (a private field) but should be referencing "Forename" (a public property).
You are referencing "Pupil.forename" but should be referencing "p.Forename".
As #MattMeadows mentioned, "==" should be used when checking for equality, not "=".
I also recommend auto properties for just setting and getting values: http://msdn.microsoft.com/en-us/library/bb384054.aspx.
Ex:
public string Forename { get; set; }

Related

C# WPF How do you set up an "Update" button to change the contents of a row on a table?

I am new to WPF and I am trying to figure out how to create an "Update" button that will show all the contents of a row on a table, allowing the user to change any category and save the new data.
What the main window would look like :
Then when the update button is clicked, a window looking like this would pop up. :
How would you make the second window? Down below is what I have to show the main window without an "update" button.
**MainWindowxaml.cs**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.IO;
namespace Sort_a_list
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public class Student
{
public string name
{
get;
set;
}
public int age
{
get;
set;
}
public string gender
{
get;
set;
}
public string major
{
get;
set;
}
public string classification
{
get;
set;
}
}
public MainWindow()
{
InitializeComponent();
List<Student> user = new List<Student>();
try
{
using (StreamReader sr = new StreamReader(#"C:\Users\justi\Documents\2021 Self Study\WPF C#\Samples.txt"))
{
string line;
char[] sep = { ',' };
int length;
ArrayList rows = new ArrayList();
while ((line = sr.ReadLine()) != null)
{
string[] words = line.Split(sep);
length = words.Length;
rows.Add(words);
}
string[] columns;
for(int i = 1; i < rows.Count; i++)
{
columns = (string[])rows[i];
user.Add(new Student() { name = columns[0], age = Int16.Parse(columns[1]), gender = columns[2], major = columns[3], classification = columns[4] });
}
}
}
catch(Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
sort.ItemsSource = user;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
Please help! Thank you very much!
You won't be able to access your Window1's DataGrid from Window2 directly.
You also not have access to your source collection (List) from Window2 to modify it from there.
In that facts, you got 2 ways:
use external database;
create public fixed collection of Students.
First of all and in any way I strongly recommend you to add some ID field to your Student object to be able unify each student.
If use external database, you can simply call something like "UPDATE students s SET s.name = #name, s.age = #age... WHERE s.ID = #id" from your Window2 when Save button clicked. #name, #age ... is new modified values
If use public fixed collection, you can access it from any part of your program.
When Window2 Save button clicked, you can search for student in it by student's ID and simply edit him. After Window2 closing you need just refresh DataGrid view by resetting ItemsSource.
It may look like this:
Student class:
public class Student
{
// Need to be unique for each student
public int ID { get; private set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Major { get; set; }
public string Classification { get; set; }
public Student(int id)
{
ID = id;
Name = "SomeName";
Age = -1;
Gender = "Unknown";
Major = "Unknown";
Classification = "None";
}
// May also be overloaded with id, id+name, id+name+age, id+name+age+gender etc
public Student(int id, string name, int age, string gender, string major, string classification)
{
ID = id;
Name = name;
Age = age;
Gender = gender;
Major = major;
Classification = classification;
}
// If you need some kind of string representation of Student
public override string ToString()
{
return $"{ID},{Name},{Age},{Gender},{Major},{Classification}";
}
}
Fixed and public collection class to store Students:
public static class DB
{
// Your actual Database, where Students would be stored
private static readonly List<Student> students = new List<Student>();
// You can get it by DB.Students from anywhere
public static List<Student> Students { get { return students; } }
// As I see you use a file as source for item collection.
// You can add some Save() method to rewrite you existing
// file with items from "database":
// public static void Save()
// {
// StringBuilder sb = new StringBuilder();
//
// foreach (Student student in students)
// {
// sb.AppendLine(student.ToString());
// }
//
// File.WriteAllText("PathToYourFile", sb.ToString());
// }
//
// You should also override ToString method in Student class
// with something like (in format you wish):
// public override string ToString()
// {
// return $"{ID},{Name},{Age},{Gender},{Major},{Classification}";
// }
}
}
Update button click handler at Window1:
private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
{
// There should be selected only 1 item or use dataGrid.SelectedItems[0]
if (dataGrid.SelectedItem is Student student)
{
// Pass selected Student to Window2
// where user will edit it
Window2 w2 = new Window2(student);
// Subscribe to Closed window to refresh DataGrid view after Student editing
w2.Closed += (s, a) =>
{
// Refresh the view of DataGrid by resetting its ItemsSource property
dataGrid.ItemsSource = null;
dataGrid.ItemsSource = DB.Students;
};
// Show update window
w2.ShowDialog();
}
}
And some kind of Window2:
public partial class Window2 : Window
{
// Here would be a copy of Student object from Window1
// with which we would manipulate in Window2
// while editing in its fields
private readonly Student editableStudent = null;
public Window2(Student student)
{
InitializeComponent();
// Copy student object to store it in our Window2
// and be able to modify it not only from Constructor
editableStudent = student;
// Fill Window2 fields with existing Student values
tbName.Text = student.Name;
tbAge.Text = student.Age.ToString();
tbGender.Text = student.Gender;
tbMajor.Text = student.Major;
tbClassification.Text = student.Classification;
// Easy "on-the-fly" subscribe to each field TextChanged handlers to check,
// whether some data was changed/edited or not
// and save it to editableStudent
tbName.TextChanged += (s, a) =>
{
// Comparing value in field with existing Student's value
if (tbName.Text != student.Name) // May also check for not empty / or for min input length
{
// Saving new value to a copied object of our Student
editableStudent.Name = tbName.Text;
}
};
// Don't forget to check for integer value
// and convert in back to int:
// Convert.ToInt32(tbAge.Text)/int.Parse(tbAge.Text)/int.TryParse(tbAge.Text, out int age)
tbAge.TextChanged += (sender, args) => { /* Do same as with Name */ };
tbGender.TextChanged += (sender, args) => { /* Do same as with Name. */ };
tbMajor.TextChanged += (sender, args) => { /* Do same as with Name */ };
tbClassification.TextChanged += (sender, args) => { /* Do same as with Name */ };
}
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
// Find index of Student element in our "Database" (List)
int index = DB.Students.FindIndex(x => x.ID == editableStudent.ID);
if (index != -1)
{
// Update record in a collection if it was found
DB.Students[index].Name = editableStudent.Name;
DB.Students[index].Age = editableStudent.Age;
DB.Students[index].Gender = editableStudent.Gender;
DB.Students[index].Major = editableStudent.Major;
DB.Students[index].Classification = editableStudent.Classification;
// Instead of use 'editableStudent' field with copied in
// constructor student's object, you can create it here
// and fill with values from TextBoxes in Window2.
// Or not create new Student object and fill new values
// directly in "database" by index.
// But you anyway need to store at least student's ID from
// student's object, passed from Window1, to be able to
// find him in "database"
// Student modifiedStudent = new Student(...);
// modifiedStudent.Name = tbName.Text;
// if (int.TryParse(tbAge.Text, out int age))
// modifiedStudent.Age = age;
// ...
// DB.Students[index].Name = modifiedStudent.Name;
// DB.Students[index].Age = modifiedStudent.Age;
// ...
// or
// DB.Students[index].Name = tbName.Text;
// if (int.TryParse(tbAge.Text, out int age))
// DB.Students[index].Age = age;
// ...
}
else
{
// Or message user if not found
MessageBox.Show("Student not found in Database (in a List of Students).");
}
// Close window after updating record in "Database"
// DataGrid view we will refresh from Window1 after
// Window2 close
Close();
}
private void ButtonCancel_Click(object sender, RoutedEventArgs e)
{
// Do nothing with Student, just close
Close();
}
}

How do I set property to zero

I need to set a label to zero. It is showing 120. There is a button that will return the required hours for this program. It is a program that returns the required hours for students major. There are 3 forms. bladah bladah yadah yadah. asdfkashdfjkhasjkdhfjkasdjkfajkdjfkajksdfjkakjshdfkjakjsdfjkashdfakjsdf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Computer_Science_Student
{
class CompSciStudent : Student
{
// Constants
private double MATH_HOURS = 20;
private double CS_HOURS = 40;
private double GEN_HOURS = 60;
// Fields
private string _academicTrack;
// Constructor
public CompSciStudent(string name, string id, string track)
: base(name, id)
{
_academicTrack = track;
}
// AcademicTrack property
public string AcademicTrack
{
get { return _academicTrack; }
set { _academicTrack = value; }
}
// RequiredHours property
public override double RequiredHours
{
get { return MATH_HOURS + CS_HOURS + GEN_HOURS; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Computer_Science_Student
{
abstract class Student
{
// Fields
private string _name;
private string _id;
// Constructor
public Student(string name, string id)
{
_name = name;
_id = id;
}
// Name property
public string Name
{
get { return _name; }
set { _name = value; }
}
// ID property
public string ID
{
get { return _id; }
set { _id = value; }
}
// RequiredHours property (abstract)
public abstract double RequiredHours
{
get;
}
}
}
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 Computer_Science_Student
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Variables to hold input
string name, id, track;
// Get the student's name and ID.
name = nameTextBox.Text;
id = idTextBox.Text;
// Get the student's academic track
if (infoSystemsRadioButton.Checked)
{
track = "Information Systems";
}
else
{
track = "Software Engineering";
}
// Create a CompSciStudent object.
CompSciStudent csStudent =
new CompSciStudent(name, id, track);
// Display the student's required hous.
requiredHoursLabel.Text =
csStudent.RequiredHours.ToString("n1");
}
private void ExitButton_Click(object sender, EventArgs e)
{
// Close the form
this.Close();
}
}
}
In your code class CompSciStudent has the following attributes and methods:
// Constants
private double MATH_HOURS = 20;
private double CS_HOURS = 40;
private double GEN_HOURS = 60;
public override double RequiredHours
{
get { return MATH_HOURS + CS_HOURS + GEN_HOURS; }
}
RequiredHours always returns sum of MATH_HOURS + CS_HOURS + GEN_HOURS, which equals 120.
Also as another person pointed out, those are not constants, they are variables. A constant would be:
const double MATH_HOURS = 20;
Here you're creating a new CompSciStudent object:
// Create a CompSciStudent object.
CompSciStudent csStudent = new CompSciStudent(name, id, track);
// Display the student's required hous.
requiredHoursLabel.Text = csStudent.RequiredHours.ToString("n1");
In your Form1_Load() method you're setting requiredHoursLabel.Text to csStudent.RequiredHours which is always 120 that's why you're seeing "120" in the text field.
The Form1_Load() method is going to be called after your form loads so it is typically used to initialize the form. So what you're doing right now is to initialize requiredHoursLabel.Text to 120.
If you have some other behavior in mind they you'll need to add something like another button besides "Close" like "OK" or "Save" or something to accept the input the user entered into the form.

No overload for method '' takes 1 argument

Well, my issue here is basically what it says in the title. I'm trying to call my bool value of my Player2 class for my Tic Tac Toe-project we have in school. I think it's worth mentioning that I use "Player Player1, Player2;" in the beginning of Form1.cs to create two instances of my class, Player. I've read multiple posts on the internet about this but all of them are people trying to call in more parameters than that they are providing. I don't see how a bool value of true or false is more than one.
Thanks in advance.
One of my buttons where this problem appears.
public void Btn1_Click(object sender, EventArgs e) >{
{
if (click1 == 0)
{
if (Player2.GetActive(true))//(turn == 0)
{
Btn1.Text = "X";
}
else
{
>Btn1.Text = "O";
}
//turn++;
click1++;
}
else
{
Btn1.Text = Btn1.Text;
}
display();
checkit();
}
}
This is my player class.
` public class Player
{
//Characteristics
string name;
int points;
bool Active;
//Constructor
public Player() { points = 0; Active = true; }
//Methods
public void SetName(string n) { name = n; }
public string GetName() { return name; }
public void SetPoints(int p) { points = p; }
public int GetPoints() { return points; }
public void SetActive(bool a) { Active = a; }
public bool GetActive() { return Active; }`
You have the code:
Player2.GetActive(true)
But you define get active as
public bool GetActive() { return Active; }`
So it is correct you have not defined a GetActive with a parameter.
Here,
if(Player2.GetActive(true))
you are passing an extra argument (true) to the method GetActive. As we can see from the method declaration of GetActive, it takes no parameters:
public bool GetActive() { return Active; }
// ↑
// empty parentheses
I think what you mean here is "if Player2.GetActive() is true..." right? You don't need to specify the value you want if it is true, just doing this is fine:
if (Player2.GetActive())
If you want to check if it is false, add ! before the call to negate the result:
if (!Player2.GetActive())
Like BugFinder said, you are using the method to get the Active-Value instead of using the method to set the value.
So change
Player2.GetActive(true)
to
Player2.SetActive(true)
Just as an addition:
Since we are working with C# here and many of your methods are called set and get, I suggest you change those methods to be properties:
public string Name
{
get { return name; }
set { name = value; }
}
public int Points
{
get { return points; }
set { points = value; }
}
public bool Active
{
get { return active; }
set { active = value; }
}
Now when you want to set the value, you can type
Player2.IsActive = true;
and to check the value simple type code like
If(Player2.IsActive)
//Do Stuff

Employee and ProductionWorker Classes, getting info from classes

I'm not completely sure the title was good for this. I'm stuck on an assignment for school there is suppose to be a video to shows how to do this but for the life of me I can't figure out how to download the student files from the pearson website. The following is the problem I'm working on.
Employee and ProductionWorker Classes
Create an Employee class that has properties for the following data:
Employee name
Employee number
Next, create a class named ProductionWorker that is derived from the Employee class. The ProudctionWorker class should have properties to hold the following data:
Shift number (an integer, such as 1, 2, or 3)
Hourly pay rate
The workday is divided into two shifts: day and night. The Shift property will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2.
Create an application that creates an object of the ProductionWorker class and lets the user enter data for each of the object's properties. Retrieve the object's properties and display their values.
Here is the code I working on for it:
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 classes
{
public partial class frmMainClasses : Form
{
string EmpShift = "";
string EmployeeName = "";
int EmployeeNumber = 0;
float HourlyPayRate = 0;
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNumber { get; set; }
}
public class ProductionWorker : Employee
{
public float HourlyPayRate { get; set; }
public Shift Shift { get; set; }
}
public enum Shift
{
Day = 1,
Night = 2
}
public frmMainClasses()
{
InitializeComponent();
}
private void btxExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnGetInfo_Click(object sender, EventArgs e)
{
string EmpShift = "";
ProductionWorker productionWorker = new ProductionWorker();
productionWorker.EmployeeName = txtName.ToString();
EmployeeName = productionWorker.EmployeeName; //Added mostly because I couldn't get EmployeeName to show anything in the messagebox
productionWorker.EmployeeNumber = Convert.ToInt32(txtIdNumb.text);
productionWorker.HourlyPayRate = Convert.ToInt32(txtPay.text);
EmpShift = Convert.ToString(txtShift.text);
txtName.Text = "";
txtIdNumb.Text = "";
txtPay.Text = "";
txtShift.Text = "";
}
private void btnShow_Click(object sender, EventArgs e)
{
MessageBox.Show("Name " + EmployeeName + "IDNumber " + EmployeeNumber + "Hourly rate " + txtPay + "Shift " + txtShift);
}
}
}
The code itself isn't showing any errors, but when I try to run it I get:
The string EmpShift thing is in there because I couldn't figure out how to work with the shift code more or less am using that as a place holder until I finger it out. I have no idea how to fix the problem, hopefully its a little mistake.
Thanks to help from the commets I was able to fix the first problem I had, now I'm having a problem with the message box at the end. The information I put into it is, Glitter for name, 12 for ID number, 1 for shift, and 12 for pay. Here's what its showing:
Name System.Windows.Forms.TextBox, Text: GlitterIDNumber 0Hourly rate
System.Windows.Forms.TextBox, Text: Shift SystemWindowsForm.TextBox, Text:
Convert.ToString doesnt give you an error because one of it calls its overload with object - public static string ToString(object value). However, since you are interested in user entered value, please use - TextBox.Text property instead of passing the TextBox.
Update 1 : some insides about this behavior
System.Convert.ToString(object value) is implemented as follows in .net -
public static string ToString(Object value, IFormatProvider provider) {
IConvertible ic = value as IConvertible;
if (ic != null)
return ic.ToString(provider);
IFormattable formattable = value as IFormattable;
if (formattable != null)
return formattable.ToString(null, provider);
return value == null? String.Empty: value.ToString();
}
therefore it ends up calling TextBox.ToString()
and System.Convert.ToInt32(object value) is as follows
public static int ToInt32(object value) {
return value == null? 0: ((IConvertible)value).ToInt32(null);
}
therefore an invalid cast exception because of this - ((IConvertible)value).ToInt32(null)
Update 2 : Code refactored for it to work
public partial class frmMainClasses : Form
{
//Change 1
//I have removed all class level string since they tend to make your code complicated & difficult to manage
//I'll replace all of them this a single instance of ProductionWorker class, a single object is easy to manage than a bunch
ProductionWorker productionWorker = new ProductionWorker(); // Creating the production Worker at class level
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNumber { get; set; }
}
public class ProductionWorker : Employee
{
public float HourlyPayRate { get; set; }
public Shift Shift { get; set; }
}
public enum Shift
{
Day = 1,
Night = 2
}
public frmMainClasses()
{
InitializeComponent();
}
private void btxExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnGetInfo_Click(object sender, EventArgs e)
{
//Change 2 : set the values of the class level variable
productionWorker.EmployeeName = txtName.Text; //.ToString(); // Change 3 removing the .ToString();
productionWorker.EmployeeNumber = Convert.ToInt32(txtIdNumb.Text);
productionWorker.HourlyPayRate = Convert.ToInt32(txtPay.Text);
productionWorker.Shift = (Shift)Enum.Parse(typeof(Shift), txtShift.Text);
//change 4 : using .ResetText() instead of Text
txtName.ResetText();// .Text = "";
txtIdNumb.ResetText();//.Text = "";
txtPay.ResetText();//.Text = "";
txtShift.ResetText();//.Text = "";
}
private void btnShow_Click(object sender, EventArgs e)
{
// change 5 : accessing class level productionWorker instead of bunch of strings
MessageBox.Show("Name " + productionWorker.EmployeeName + " IDNumber " + productionWorker.EmployeeNumber + " Hourly rate " + productionWorker.HourlyPayRate + " Shift " + productionWorker.Shift);
}
}
I've added comments to elaborate what all changes I've made, please write me a comment if you have any questions.
Also, at the moment your code does not validate user inputs in text boxes.

Replace TextBox with int

I have the following, and it works:
My player class:
public Player(string Str, string SP)
{
Strength = Str;
StatPoints = SP;
}
public string StatPoints
{
get;
set;
}
public string Strength
{
get;
set;
}
Now on my form1 I have a textbox, and a button. The button increments the value in the textbox by one so long as there is a value above 0 in the SP textbox. Problem is, I am declaring six variables in order to manage two values because I have to convert strings to ints and all that crap. Is there a way to replace text boxes with something that is inherently int? Here is my character sheet code so far.
private void AddButton_Click(object sender, EventArgs e)
{
Player PCStats = new Player(StrBox.Text, SPBox.Text);
int IntPCSP = Convert.ToInt16(PCStats.StatPoints);
int IntPCStr = Convert.ToInt16(PCStats.Strength);
if (IntPCSP >= 1 && IntPCStr <= 7)
{
IntPCStr++;
IntPCSP--;
PCStats.Strength = IntPCStr.ToString();
PCStats.StatPoints = IntPCSP.ToString();
StrBox.Text = PCStats.Strength;
SPBox.Text = PCStats.StatPoints;
}
else
{
MessageBox.Show("Earn more experience!");
}
/*
MessageBox.Show("PCStats.StatPoints equals" + PCStats.StatPoints);
MessageBox.Show("PCStats,Strength equals" + PCStats.Strength);
MessageBox.Show("IntPCSP Equals" + IntPCSP.ToString());
MessageBox.Show("IntPCStr Equals" + IntPCStr.ToString());
*/
}
Or is there an even easier way to do this I completely overlooked. I was super excited to finally get this bit to work after a lot of trial and error, but I am open to redoing it. I would rather however just replace the text boxes so I am not converting variables all over the place.
This is quick go, not at a computer with Visual Studio on it but should give you a start. Also, try naming your variables etc to have a bit more meaning. Also, this is to fix what you has as-is but see my update / suggestion further down about moving logic into the Player class...
My player class:
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
public int StatPoints { get; set; }
public int Strength { get; set; }
My Form:
private void AddButton_Click(object sender, EventArgs e)
{
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.StatPoints > 0 && thePlayer.Strength < 8)
{
thePlayer.Strength++;
thePlayer.StatPoints--;
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
Obviously you would need to check that the values in the text box were integers. You could use another control, mask the text box etc or on the code replace int.Parse with int.TryParse which checks it is possible before conversion. Just a few ideas to get you going!
- UPDATE -
Another thing you could do is more the logic into the Player class. This is better as it keep the logic contained in one place so you can see what a Player can DO rather than having to search the whole program:
New Player class:
// The Player class
public class Player
{
// Constructor
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
// Method to gain strength if enough StatPoints
public bool GainStrength()
{
bool playerHasEnoughStatPoints = true;
if (this.StatPoints < 1)
{
playerHasEnoughStatPoints = false;
}
else if (this.Strength < 8)
{
this.Strength++;
this.StatPoints--;
}
return playerHasEnoughStatPoints;
}
// Property for StatPoints
public int StatPoints { get; set; }
// Property for Strength
public int Strength { get; set; }
}
New Form:
// The Form or similar
public class MyFormOrSimilar
{
// When button pressed try and add strength to the player
protected void AddButton_Click(object sender, EventArgs e)
{
// Create new INSTANCE of the player and try to give them strength
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.GainStrength())
{
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
}

Categories

Resources