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!");
}
}
}
Related
I'm pretty new to C#. I want to increment an int variable id by 1 and insert it into a datagridview. The problem is, it doesn't increment, it stays at 1.
Here's my code for adding the data to datagridview
class QuantityCtrl : Quantity
{
private ManageSale _manageSale;
public QuantityCtrl(ManageSale manageSale)
{
_manageSale = manageSale;
}
private void BtnOk_Click(object sender, EventArgs e)
{
_manageSale.dgvItemList.Rows.Add
(
GenerateId(),
_manageSale.lblName.Text,
_manageSale.lblPrice.Text,
_manageQuantity.txtDiscount.Text,
_manageQuantity.txtQuantity.Text,
Total
);
}
}
Here's my code for incrementing
class Quantity
{
public int OrderId = 1;
public int GenerateId()
{
return OrderId++;
}
}
Another way of doing it would be creating a new class in a folder inside your solution which contains the list and the proprieties :
class IDS
{
#region Proprieties
public int Id { get; set; }
#endregion
#region Lists
public List<IDS> _ids = new List<IDS>();
#endregion
}
Now, you'll need to link the class to the main, for that, go in your main code and put at the top :
using SolutionName.Folder;
Next go to your button event and simply put this:
private void btnAutoGen_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
int iId = 0;
try
{
var req = (from value in _id
select value.Id).Max() + 1;
iId = req;
}
catch (InvalidOperationException)
{
iId = 1;
}
You now have a button that auto increment.
I solved it thanks to Brendan. I hope it could be a referrence for some developers :) and If someone has a better way of incrementing you can answer it Thank you.
public static int OrderId = 1;
In my Windows form I have 2 text boxes namely, start odometer reading and end odometer reading. My goal is to subtract the "start reading" from the "end reading" and display the difference in the label next to the Name and phone number of the client in the windows form label.
How do I return the value of the method getMilesCharge() and display it on the confirmLabel?
Code for the Car Rental Class
//A class that represents the Rental Agency Class.
namespace Assignment1
{
partial class RentalAgencyClass
{
//instance variables
public string customerName { get; set; }
public string phoneNumber { get; set; }
public double sMiles { get; set; }
public double eMiles { get; set; }
public double noOfDays { get; set; }
private double DAY_CHARGE = 15;
private double MILE_CHARGE = 0.12;
//Constructor class
//sets the value of the starting and ending miles.
//sets the value of the number of days the car was rented for
public RentalAgencyClass(double startMiles, double endMiles, double days)
{
startMiles = sMiles;
endMiles = eMiles;
days = noOfDays;
}
//method to calculate the number of miles driven on the rental
public double getMileCharge()
{
double milesDriven = 0;
milesDriven = eMiles - sMiles;
return milesDriven * MILE_CHARGE;
}
//method to calculate the Day Charges on the rental
public double getDayCharge()
{
return noOfDays * DAY_CHARGE;
}
//Property to display the information on the label
public string GetInfo()
{
return customerName + " | " + phoneNumber + " | " + getDayCharge() +" miles";
}
}
}
Form Designer Class code
namespace Assignment1
{
public partial class RentalAgencyClass : Form
{
RentalAgencyClass aCarRental;
public RentalAgencyClass()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
//instantiates object
aCarRental = new RentalAgencyClass();
aCarRental.customerName = nameTextBox.Text;
aCarRental.phoneNumber = phoneTextBox.Text;
//aCarRental. = getDayCharge();
// aCarRental.milesDriven = //store the difference in this variable
//displayLabel.Text = "(student information saved)";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error");
}
//Displays information about the Rental
confirmLabel.Text = aCarRental.GetInfo();
}
}
}
By calling aCarRental = new RentalAgencyClass(); within your calculateButton_Click method you are calling the parameterless constructor of your partial class RentalAgencyClass, which means in your case, you are creating a new instance of your form instead of setting your properties. So sMiles and eMiles will stay by their default value 0.
To get your code working you have to do several steps.
At first I recommend you should split your form and your agency class.
So let's say, rename your form class to RentalCalculator. As a next step you have to/can remove the partial from your RentalAgencyClass, because it is not a part of your form class anymore and I assume you did not want to extend your class in another part of your code.
As LarsTech pointed out in the comments. You should now fix your RentalAgencyClass constructor to:
public RentalAgencyClass(double startMiles, double endMiles, double days)
{
this.sMiles = startMiles;
this.eMiles = endMiles;
this.noOfDays = days;
}
and may add the following property to your class
public double milesDriven
{
get
{
return this.eMiles - this.sMiles;
}
}
At least you have to change your event handler:
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
// if not existing you have to create some input textboxes
double startMiles = Convert.ToDouble(startMilesTextBox.Text);
double endMiles = Convert.ToDouble(endMilesTextBox.Text);
double days = Convert.ToDouble(daysTextBox.Text);
// Hint: you are creating a new instance on every button click
// and overwriting your field in your form class.
aCarRental = new RentalAgencyClass(startMiles, endMiles, days);
aCarRental.customerName = nameTextBox.Text;
aCarRental.phoneNumber = phoneTextBox.Text;
// Store the result in local variables
// if you want to do something with them later
double dayCharge = aCarRental.getDayCharge();
double milesCharge = aCarRental.getMilesCharge();
double drivenMiles = aCarRental.milesDriven;
// displayLabel.Text = "(student information saved)";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error");
}
//Displays information about the Rental
confirmLabel.Text = aCarRental.GetInfo();
}
Answering your question:
How do I return the value of the method getMilesCharge() and display it on the confirmLabel?
You will have to change the following line in your calculateButton_Click method from:
confirmLabel.Text = aCarRental.GetInfo();
to:
confirmLabel.Text = aCarRental.getMilesCharge().ToString();
Last but not least let me give you a kind advice.
You may take a look at the Microsoft Naming Guidelines.
For example: Properties should be named in PascalCasing.
But this is just my personal opinion.
So, I'm at a loss here. Have a small project to work on. Have to create a trip class then create a Windows Form app and use the class I created to use the form to calculate miles per gallons used and Cost Per Mile.
Have completed the class:
namespace TripCalculator
{
class Trip
{
//Data members of class
private string destination;
private double distTrav;
private double totalCostGas;
private double numGallonsGas;
//Default Constructor
public Trip()
{
}
//Constructor with all parameters
public Trip(string tripDest, double milesTrav, double ttlPriceGas, n double numGalls)
{
destination = tripDest;
distTrav = milesTrav;
totalCostGas = ttlPriceGas;
numGallonsGas = numGalls;
}
//Propery for destination data field
public string Destination
{
set
{
destination = value;
}
get
{
return destination;
}
}
public double DistTrav
{
set
{
distTrav = value;
}
get
{
return distTrav;
}
}
public double TotalCostGas
{
set
{
totalCostGas = value;
}
get
{
return totalCostGas;
}
}
public double NumGallonsGas
{
set
{
numGallonsGas = value;
}
get
{
return numGallonsGas;
}
}
public double CalculateMPG()
{
return (distTrav / numGallonsGas);
}
public double CalculateCPM()
{
return (totalCostGas / numGallonsGas);
}
public override string ToString()
{
return CalculateMPG().ToString();
}
}
}
I want to be able to input destination, distance, cost, and gallons of gas into the form. Then I want the mpg and cost per mile to return to me in a textboxes.
Here's the form.cs
namespace TripCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calcBtn_Click(object sender, EventArgs e)
{
string destination;
double distTrav;
double totalCostGas;
double numGallonsGas;
destBox.Focus();
distBox.Focus();
gasBox.Focus();
galBox.Focus();
Trip aTrip = new Trip (destination, distTrav, totalCostGas, numGallonsGas );
mpgTxt.Text = aTrip.CalculateMPG().ToString();
cpmTxt.Text = aTrip.CalculateCPM().ToString();
destBox.Enabled = false;
}
}
}
Im getting 4 errors saying "Use of unassigned local variable 'destination' (As well as for the other 3 variables above). It'll start the program, but returns nothing when I type in the text boxes and click the button. What am I doing wrong? Please help! Thanks.
private void calcBtn_Click(object sender, EventArgs e)
{
string destination; // Give value for these
double distTrav; // Give value for these
double totalCostGas; // Give value for these
double numGallonsGas; // Give value for these
}
Assign some value, either from user input or hard coded value for testing
Something like the code below, where you get the values from the text box in your Winform assuming you have such text boxes.
string destination = DestinationTextBox.Text;
double distTrav = double.Parse(DistTravTextBox.Text);
double totalCostGas = double.Parse(TotalCostGasTextBox.Text);
double numGallonsGas = double.Parse(NumGallonsGasTextBox.Text);
You need to set the textbox values for the variables
string destination = txtDestination.Text;
double distTrav = double.Parse(txtTrav.Text);
double totalCostGas = double.Parse(txtCostGas.Text);
double numGallonsGas = double.Parse(GallonsGas.Text);
Taking a C#.Net class and we have been introduced a new concept of using a class with a form. It's an online class and basically the instructor has given us instructions, however they are somewhat unclear, at least to me. Unfortunately, his responses to students questions are very vague and basically, in a nut shell, told us to figure it out, so I be here. Below is what the instructor gave us.
=========================================================================
UML: Model: String, CurrentSpeed: Decimal, TopSpeed: Decimal, and Accelerate (change speed: Decimal)
Accelerate adds changeSpeed (which can be positive, negative or 0) to CurrentSpeed. CurrentSpeed can never exceed TopSpeed or be less than 0
e.g. if CurrentSpeed is 10 and dChangeSpeed is -20, CurrentSpeed becomes 0
General Requirements:
Top Speed combo box is filled with numbers 60, 70, 80 …. 200
(at Run time)
Change Speed combo box is filled with numbers 1, 2, 3 ….200
(at Run time)
User must select from combo box (cannot enter own numbers)
Button Action Requirements:
Accelerate For same model, increases Current Speed by Change Speed
For new model, sets Current Speed to Change Speed
(Current Speed can’t exceed Top Speed)
Decelerate For same model, decreases Current Speed by Change Speed
For new model, sets Current Speed to 0
(Current Speed can’t go below 0)
UML diagram is followed exactly.
Work (calculations, etc) done in the class, not the form.
=========================================================================
Ok, so my question is, should I use a Deceleration method, along with the Accelerate in the class? I'm assuming that each button (decel, accel) would need its own method in the class. However I think I'm overly making this complicated, which was the answer to one of my question I asked my instructor. I guess I'm totally stumped as to how to reference the class, specifically the Accelerate with the form.
So far, this is what I came up with, which I know is mostly wrong, however this is a beginners class from what I'm told and the support form the instructor is not there other than relying on a chapter about classes.
public class Car
{
// Backing Fields (Instance Variables)
private string _model;
private int _currentSpeed;
private int _topSpeed;
public int SpeedResult;
// Set Parameters
public Car()
{
this.Model = "";
this.CurrentSpeed = 0;
this.TopSpeed = 0;
}
// Constructor
public Car(string Model, int CurrentSpeed, int TopSpeed)
{
_model = Model;
_currentSpeed = CurrentSpeed;
_topSpeed = TopSpeed;
}
// Model Property
public string Model
{
get { return _model; }
set { _model = value; }
}
// Current Speed Property
public int CurrentSpeed
{
get { return _currentSpeed; }
set { _currentSpeed = value; }
}
// Top Speed Property
public int TopSpeed
{
get { return _topSpeed; }
set { _topSpeed = value; }
}
// Methods
public int Accelerate()
{
SpeedResult = (TopSpeed + CurrentSpeed);
return SpeedResult;
}
//
public void clear()
{
Model = "";
CurrentSpeed = 0;
TopSpeed = 0;
}
}
Form:
public partial class carSpeedForm : Form
{
private Car _myCar;
private int SpeedResult;
public carSpeedForm()
{
_myCar = new Car();
InitializeComponent();
}
private void carSpeedForm_Load(object sender, EventArgs e)
{
// Loads Amount ComboBox with values from 60 to 200 in increments of 10
for (int i = 60; i <= 200; i += 10)
topSpeedComboBox.Items.Add(i);
// Loads Amount ComboBox with values from 1 to 200 in increments of 1
for (int i = 1; i <= 200; i += 1)
changeSpeedComboBox.Items.Add(i);
}
private void GetCarData()
{
try
{
_myCar.Model = carModelTextBox.Text;
_myCar.TopSpeed = int.Parse(topSpeedComboBox.Text);
_myCar.CurrentSpeed = int.Parse(changeSpeedComboBox.Text);
}
catch
{
MessageBox.Show(string.Concat("Please enter a valid model and speed(s) for vehicle.","\r\n"));
}
}
private void accelButton_Click(object sender, EventArgs e)
{
GetCarData();
speedResultLabel.Text = SpeedResult.ToString("n1");
carResultLabel.Text = String.Format("Your car is a new car.");
}
private void decelButton_Click(object sender, EventArgs e)
{
GetCarData();
speedResultLabel.Text = SpeedResult.ToString("n1");
carResultLabel.Text = String.Format("Your car is a new car.");
}
private void clearButton_Click(object sender, EventArgs e)
{
//Clear textbox, combobox, labels
carModelTextBox.Clear();
carModelTextBox.Focus();
topSpeedComboBox.SelectedIndex = -1;
changeSpeedComboBox.SelectedIndex = -1;
speedResultLabel.Text = "";
carResultLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
//Close application
this.Close();
}
}
Not only is your code not “mostly wrong”, I’d even call it mostly right. It is not clear exactly what you are asking, or what “how to reference the class” means.
The instructor is right to tell you to “to figure it out”, and we can’t do your assignment for you. If you have working code you want people to review, post it on the Code Review site.
However, there are a few code smells that, in my experience, will lead to problems in the future:
// Backing Fields (Instance Variables)
Do not comment programming terms; they contribute nothing and soon go out of sync with the code. Only comment things that cannot be expressed in the programming language.
private string _model;
// Model Property
public string Model
{
get { return _model; }
set { _model = value; }
}
That’s about the most verbose way possible to define a property. Defining separate backing fields only encourages people to use the backing field instead of the property. Moreover, making it public makes any consumer of the class able to change the property at any time. Sometimes you need those things, but you should not allow them unless you absolutely need them. Also, vague names like “Model” are hard to understand, especially if other classes use them. A better definition would be:
public string ModelName { get; private set; }
public int SpeedResult;
What is this? It’s not in your UML, and is never used for anything. Moreover, it’s public so anything can change it to anything; it’s totally useless, get rid of it.
// Set Parameters
public Car()
{
this.Model = "";
this.CurrentSpeed = 0;
this.TopSpeed = 0;
}
And then in your form constructor:
_myCar = new Car();
This is worse than useless; you’re creating instances that contain no data, and every field is public so anything can change your data to anything. C# gives you the ability to enforce that your instances only contain valid data. Use them, and only create an instance when you know its data. You should have only one Car constructor like this:
public Car(string modelName, float topSpeed)
{
if (string.IsNullOrWhiteSpace(modelName)) throw new ArgumentNullException("modelName");
ModelName = modelName;
TopSpeed = topSpeed;
}
I assume CurrentSpeed is mutable, so you probably shouldn’t define it in the constructor; it is a candidate for one of those public properties I warned you about.
public int Accelerate()
{
SpeedResult = (TopSpeed + CurrentSpeed);
return SpeedResult;
}
Why would you add TopSpeed to CurrentSpeed? That can make SpeedResult greater than TopSpeed. Why are your speeds ints? Your description calls them “decimal”, but the C# decimal type is for fixed-point values. float is a better choice.
Your question says “Accelerate adds changeSpeed ... to CurrentSpeed ... CurrentSpeed can never exceed TopSpeed or be less than 0”. So do that:
public void Accelerate(float changeSpeed)
{
var predictedSpeed = CurrentSpeed + changeSpeed;
if (predictedSpeed > TopSpeed)
CurrentSpeed = TopSpeed;
else if (predictedSpeed < 0)
CurrentSpeed = 0;
else
CurrentSpeed = predictedSpeed;
}
public void clear()
{
Model = "";
CurrentSpeed = 0;
TopSpeed = 0;
}
Again, you're allowing anything at all to wreck your data. Don't do that; if you need to create a new car, then create a new Car. If you don’t want to display a car, don’t create one.
There are problems with your carSpeedForm as well, but I see MGM is addressing those.
Reading the description you wrote, it looks like you basically have the concept down. From your form, I assume you will be selecting a car type? If that is the case, you basically want to define all your model(Car) behavior in a Car class.
For example, as you have already done, you would want to define accessors for the selected cars data and the Accelerate and Decelerate methods. That way inside you view(carSpeedForm) you can call the perspective method when the corresponding button is pressed. I.E. if the user presses the Accelerate button on the form, you would call the Accelerate method of the instance of Car. Hope that helps. You're not far off.
You should use the button and input controls to store the data in your_myCar instances. For Example
public partial class CarForm : Form
{
private Car theCar;
private bool modelChanged;
public CarForm()
{
theCar = new Car();
InitializeComponent();
loadChangeSpeed_cb();
loadTopSpeed_cb();
modelChanged = false;
}
private void loadChangeSpeed_cb()
{
for (decimal i = 1; i <= 200; i++)
{
changeSpeed_cb.Items.Add(i);
}
}
private void loadTopSpeed_cb()
{
for(decimal i = 60; i <= 200; i+=10)
{
topSpeed_cb.Items.Add(i);
}
}
private void accel_b_Click(object sender, EventArgs e)
{
if(modelChanged)
{
theCar.CurrentSpeed = theCar.ChangeSpeed;
modelChanged = false;
}
else
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.Accelerate((decimal)si);
}
}
private void decel_b_Click(object sender, EventArgs e)
{
if(modelChanged)
{
theCar.CurrentSpeed = 0;
modelChanged = false;
return;
}
else
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.Accelerate(-(decimal)si);
}
}
private void topSpeed_cb_SelectedIndexChanged(object sender, EventArgs e)
{
var si = topSpeed_cb.SelectedItem;
if(si == null)
{
return;
}
theCar.TopSpeed = (decimal)si;
}
private void changeSpeed_cb_SelectedIndexChanged(object sender, EventArgs e)
{
var si = changeSpeed_cb.SelectedItem;
if (si == null)
{
return;
}
theCar.ChangeSpeed = (decimal)changeSpeed_cb.SelectedItem;
}
I'm creating a form to hold information from "meetings". The user will fill out info regarding title, location, startTime, endTime, notes, and a date. What I am currently working on is the "save changes" button which will:
clear all the TextBoxes.
store the input in an array.
display only the title in the ListBox.
when the title is clicked on in the ListBox, the info stored in that array element re-populates in the appropriate TextBoxes should the user wish to make changes.
I have completed #1, #2 and #3 I would appreciate any help for #4. I've pasted the coding below for your viewing.
public partial class CalendarForm : Form
{
int currentIndex;
int arraySize = 0;
Meeting[] meetingArray = new Meeting[100];
public CalendarForm()
{
InitializeComponent();
}
private void saveChangesButton_Click(object sender, EventArgs e)
{
meetingArray[arraySize] = new Meeting();
meetingArray[arraySize].title = textBoxTitle.Text;
meetingArray[arraySize].location = textBoxLocation.Text;
meetingArray[arraySize].startTime = textBoxStartTime.Text;
meetingArray[arraySize].endTime = textBoxEndTime.Text;
meetingArray[arraySize].notes = notesTextBox.Text;
currentIndex = arraySize;
arraySize++;
meetingListBox.Enabled = true;
textBoxTitle.Text = "";
textBoxLocation.Text = "";
textBoxStartTime.Text = "";
textBoxEndTime.Text = "";
notesTextBox.Text = "";
*edit* added these two lines which now add the title to the listBox
meetingListBox.Items.Add(meetingArray[currentIndex].title);
Controls.Add(meetingListBox);
}
}
public class Meeting
{
public string title;
public string location;
public string startTime;
public string endTime;
public string notes;
};
This is how I would refactor the class:
public partial class CalendarForm : Form
{
private List<Meeting> Meetings { get; set; }
public CalendarForm()
{
InitializeComponent();
Meetings = new List<Meeting>();
}
private void saveChangesButton_Click(object sender, EventArgs e)
{
try
{
Meeting meeting = CreateMeeting();
Meetings.Add(meeting);
meetingListBox.Add(meeting);
}
catch
{
//Add proper error handling here
}
}
private Meeting CreateMeeting()
{
return new Meeting()
{
Title = textBoxTitle.Text,
Location = textBoxLocation.Text
StartTime = DateTime.Parse(textBoxStartTime.Text),
EndTime = DateTime.Parse(textBoxEndTime.Text),
Notes = notesTextBox.Text,
};
}
}
//As Matt Burland answered already:
private void meetingListBox_SelectedIndexChanged(object sender, EventArgs e)
{
Meeting meeting = meetingListBox.SelectedItem as Meeting;
if (meeting != null)
{
textBoxTitle.Text = meeting.Title;
//...etc for all your other text boxes.
}
}
public class Meeting
{
public string Title { get; set; }
public string Location { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Notes { get; set; }
public override string ToString()
{
return Title;
}
}
I've made a number of changes, more notably the switch from an Array to a List<>. Lists are more flexible and provide better functionality. Unless you really really need to use arrays, I would stay away from them just to better safeguard against logic errors index out of bounds type issues.
Also, I personally believe that dates should be stored in the DateTime struct format, but that is again a matter of preference. Note that it would be prudent to sanitize/validate the inputs (especially the dates) before assigning it into the Meeting object.
The Meeting object now has properties instead of public fields. Properties are preferred in case you ever want to change how something is Get/Set.
Hope this helps.
I really recommend you look up data binding and learn how to do this properly, but if you want a quick and dirty solution (although, in the end, you'll find it's a lot more work), I would do something like this:
private void saveChangesButton_Click(object sender, EventArgs e)
{
Meeting m = new Meeting();
m.title = textBoxTitle.Text;
m.location = textBoxLocation.Text;
m.startTime = textBoxStartTime.Text;
m.endTime = textBoxEndTime.Text;
m.notes = notesTextBox.Text;
meetingArray[arraySize] = m;
currentIndex = arraySize;
arraySize++;
meetingListBox.Enabled = true;
textBoxTitle.Text = "";
textBoxLocation.Text = "";
textBoxStartTime.Text = "";
textBoxEndTime.Text = "";
notesTextBox.Text = "";
meetingListBox.Items.Add(m);
//Controls.Add(meetingListBox); // You don't need to keep adding the control every time!
}
Now in your Meeting class, I'd override ToString() to just return the title. The ListBox will just use the ToString() method of whatever you add to it by default.
To help with #4, you want to bind the SelectedIndexChanged event and then use the SelectedItem property, cast it back to a Meeting object (because it'll return an Object) and then use it to repopulate your various text boxes.
Something like:
private void meetingListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
Meeting m = meetingListBox.SelectedItem as Meeting;
if (m != null)
{
textBoxTitle.Text = m.title;
//...etc for all your other text boxes.
}
}