I am currently writing a program which reads data in from a text file. The problem I am currently having is that the CompareTo method below is coming up with the error System.StackOverflowException was unhandled and saying "Make sure you don't have an infinite loop or infinite recursion. This error appears on the line return name.CompareTo(temp.name);.
The whole class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Country
{
public class Country : IComparable
{
// Country Properties
private String name;
private float gdpGrowth;
private float inflation;
private float tradeBalance;
private float hdiRanking;
private LinkedList<String> tradePartners;
//Constructor
public Country(String name, float gdpGrowth, float inflation, float tradeBalance, float hdiRanking, LinkedList<String> tradePartners)
{
this.name = name;
this.gdpGrowth = gdpGrowth;
this.inflation = inflation;
this.tradeBalance = tradeBalance;
this.hdiRanking = hdiRanking;
this.tradePartners = tradePartners;
}
public String Name
{
set { this.name = value; }
get { return name; }
}
public float GdpGrowth
{
set { this.gdpGrowth = value; }
get { return gdpGrowth; }
}
public float Inflation
{
set { this.inflation = value; }
get { return inflation; }
}
public float TradeBalance
{
set { this.tradeBalance = value; }
get { return tradeBalance; }
}
public float HdiRankings
{
set { this.hdiRanking = value; }
get { return hdiRanking; }
}
public LinkedList<String> TradePartners
{
set { this.tradePartners = value; }
get { return tradePartners; }
}
public override string ToString()
{
return name + ", " + gdpGrowth + ", " + inflation + ", " + tradeBalance + ", " + hdiRanking + ", " + tradePartners;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return name.CompareTo(temp.name);
}
}
}
The class which is calling the country class is...
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;
using System.IO;
namespace Country
{
public partial class Form1 : Form
{
private AVLTree<Country> countryTree = new AVLTree<Country>();
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// array to stroe each line of the file
String[] Lines = new string[1000];
String[] tempPartners = new string[1000];
int count = 0;
// Store each line of the file in the eachLine array
Lines = File.ReadAllLines("countries.csv");
foreach (String line in Lines)
{
if (count == 0)
{
count++;
}
else
{
// array to hold info
String[] info = new string[5];
//splits the countries
info = line.Split(',');
// split trade partners and puts in array
tempPartners = info[5].Split(';', '[', ']');
// insert current instance of country into AVL Tree
countryTree.InsertItem(new Country(info[0], float.Parse(info[1]),
float.Parse(info[2]), float.Parse(info[3]), float.Parse(info[4]), new LinkedList<String>(tempPartners)));
// create seperator
string seperator = ", ";
// stroe array
string partners = string.Join(seperator, tempPartners);
// remove first comma
partners = partners.Substring(1, partners.Length - 1);
//remove last comma
partners = partners.Remove(partners.Length - 2);
//pass in information from file into grid view
dataGridView1.Rows.Add(info[0], info[1], info[2], info[3], info[4], partners);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You've got infinite recursion going here. CompareTo makes a recursive call but doesn't terminate due to the lack of a base case, so the recursive stack grows infinite. No actual comparison takes place either. What integer values do you want this to return, and under what conditions?
Perhaps as CyberDude said, you're really trying to use String.Compare(name, temp.name)?
Related
I have the .txt files inside the project's debug folder but the listboxes still won't display any of the data.
I've already missed the due date for this project, I just have a very unhelpful professor and I'd love to learn what I did wrong. Thanks!
The overview of what I'm trying to do here is:
Display delimited data into three listboxes from three text files. When a user clicks on an item in the listbox, one line of additional data (an ID) will be displayed in a textbox underneath that listbox. All three listboxes are shown on the same form and all data is delimited using the same character.
Here is 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;
using System.IO;
namespace LabDay2Modified
{
struct CustomersNames
{
public string custID;
public string firstName;
public string lastName;
public string accountID;
}
struct AccountNumbers
{
public string acctID;
public string accountType;
public string accountNumber;
public string accountAmt;
}
struct LoanInfo
{
public string loanID;
public string loanYears;
public string loanIntRate;
public string loanAmt;
public string customerID;
public string loanType;
}
public partial class Form1 : Form
{
private List<CustomersNames> customerList = new List<CustomersNames>();
private List<AccountNumbers> accountList = new List<AccountNumbers>();
private List<LoanInfo> loanList = new List<LoanInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadCustFile()
{
try
{
StreamReader inputFile;
string line;
CustomersNames entry = new CustomersNames();
char[] delim = { ',' };
inputFile = File.OpenText("customers.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.custID = tokens[0];
entry.firstName = tokens[1];
entry.lastName = tokens[2];
entry.accountID = tokens[3];
customerList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadAcctFile()
{
try
{
StreamReader inputFile;
string line;
AccountNumbers entry = new AccountNumbers();
char[] delim = { ',' };
inputFile = File.OpenText("accounts.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.acctID = tokens[0];
entry.accountNumber = tokens[1];
entry.accountType = tokens[2];
entry.accountAmt = tokens[3];
accountList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadLoanFile()
{
try
{
StreamReader inputFile;
string line;
LoanInfo entry = new LoanInfo();
char[] delim = { ',' };
inputFile = File.OpenText("loans.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.customerID = tokens[0];
entry.loanID = tokens[1];
entry.loanType = tokens[2];
entry.loanYears = tokens[3];
entry.loanIntRate = tokens[4];
entry.loanAmt = tokens[5];
loanList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CustInfo()
{
foreach(CustomersNames entry in customerList)
{
customerListBox.Items.Add(entry.custID + " " + entry.firstName + " " + entry.lastName);
}
}
private void AcctInfo()
{
foreach (AccountNumbers entry in accountList)
{
accountListBox.Items.Add(entry.accountNumber + " " + entry.accountType + " " + entry.accountAmt);
}
}
private void LoansInfo()
{
foreach (LoanInfo entry in loanList)
{
loanListBox.Items.Add(entry.loanID + " " + entry.loanType + " " + entry.loanYears+" "+entry.loanIntRate+" "+entry.loanAmt);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = customerListBox.SelectedIndex;
customerAccountID.Text = "Account ID: " + customerList[index].accountID;
}
private void loanListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = loanListBox.SelectedIndex;
loanCustomerID.Text = "Customer ID: " + loanList[index].customerID;
}
private void accountListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = accountListBox.SelectedIndex;
accountAccountID.Text = "Account ID: " + accountList[index].acctID;
}
private void Form1_Load(object sender, EventArgs e)
{
ReadCustFile();
CustInfo();
ReadAcctFile();
AcctInfo();
ReadLoanFile();
LoansInfo();
}
}
}
You can use the following .txt file to see if it works for you.
Then, you will get the following result.
Besides, you can set the similar style for other txt files.
I have a working application that compiles and everything. The two buttons work, however I need them to add/decrease 5 from the speed with every single click and currently they will only let me click once and accelerate gives me an answer of 5 for speed, while decelerate gives -5. How can I change this to allow for each button to be clicked and the speed update more than once?
Here is the form:
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 Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData()
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
lblAnswer.Text = " Your car is a " + myCar.Year + " " + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ";
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
lblAnswer.Text = " Your car is a " + myCar.Year + " " + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ";
}
}
}
Here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return year; }
set { year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
Since this is probably homework I'll just give hints. With both click functions, the first call you make is to GetCarData(). Inside GetCarData(), you're calling myCar.Speed = 0;, so it's not surprising that you're going back to square one with each click.
Assuming that you want only one instance of Car for your entire application, you just need to modify the insides of GetCarData() to do (or not do) what you want. Just a few tweaks in that function, which I'll let you experiment with, and you'll be good to go.
However, if you want multiple Car objects in your app, you're going to need to modify it to have some kind of List (or better yet, an IDictionary).
I'm new here, and also new in C# programming in Visual Studio.
Currently I have an assignment about C# refactoring.
This is the original class
calculator.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 HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
public calculator()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void calorieCalculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = (66
+ (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
}
else
{
txtCalories.Text = (655
+ (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
}
}
private void weightCalculation()
{
double maleVariable = 50;
double femaleVariable = 45.5;
double Formula = (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12) + Convert.ToDouble(txtInches.Text)));
if (rbtnMale.Checked)
{
txtIdealWeight.Text = ((maleVariable + Formula) * 2.2046).ToString();
}
else
{
txtIdealWeight.Text = ((femaleVariable + Formula) * 2.2046).ToString();
}
}
private void txtFeetValidation()
{
double feet;
if (!double.TryParse(txtFeet.Text, out feet))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
}
}
private void txtInchesValidation()
{
double inches;
if (!double.TryParse(txtInches.Text, out inches))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
}
private void txtWeightValidation()
{
double weight;
if (!double.TryParse(txtWeight.Text, out weight))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
}
private void txtAgeValication()
{
double age;
if (!double.TryParse(txtAge.Text, out age))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtFeetValidation();
txtInchesValidation();
txtWeightValidation();
txtAgeValication();
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
calorieCalculation();
weightCalculation();
}
private void label8_Click(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAddPatient_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtIdealWeight.Text))
{
Form secondForm = new patientInfo(this);
secondForm.Show();
}
else
{
MessageBox.Show("Please enter all datas and click on 'Add Patient' to add patient's records");
}
}
private void btnPatientList_Click(object sender, EventArgs e)
{
Form secondForm = new patientList(this);
secondForm.Show();
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
The following classed are the parent class and sub-classes I would like to setup.
parent: calculator.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 HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
//private string maleCaloriesCalculation();
//private string maleWeightCalculation();
//private string femaleCaloriesCalculation();
//private string femaleWeightCalculation();
public calculator()
{
InitializeComponent();
}
private void rbtnMale_CheckedChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
/* Validate User Input: */
//Validate height (feet) is numeric value
double result;
if (!double.TryParse(txtFeet.Text, out result))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
return;
}
//Validate height (inches) is numeric value
if (!double.TryParse(txtInches.Text, out result))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
//Validate weight is numeric value
if (!double.TryParse(txtWeight.Text, out result))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
//Validate age is numeric value
if (!double.TryParse(txtAge.Text, out result))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
/*End validation*/
calculation();
}
private void calculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = maleCalculator.maleCalories().ToString();
//txtCalories.Text = maleCalculator.maleCaloriesCalculation();
//txtIdealWeight.Text = maleCalculator.maleWeightCalculation();
}
else
{
txtCalories.Text = femaleCalculator.femaleCaloriesCalculation();
txtIdealWeight.Text = femaleCalculator.femaleWeightCalculation();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
}
}
subclass: maleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class maleCalculator: calculator
{
//private string maleCaloriesCalculation;
//private string maleWeightCalculation;
public maleCalculator maleCalories()
{
(66 + (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
return maleCalories();
//this.txtCalories.Text = new maleCalculator.maleCalories;
}
public maleCalculator maleWeight()
{
((50 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return maleWeight();
}
}
}
subclass: femaleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class femaleCalculator : calculator
{
public double femaleCaloriesCalculation()
{
txtCalories.Text = (655 + (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
return femaleCaloriesCalculation();
}
public double femaleWeightCalculation()
{
txtIdealWeight.Text = ((45.5 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return femaleWeightCalculation();
}
}
}
As we can see, these two sub-classes are use to do the calculation for the calories and ideal weight. They are plan to take place of private void calorieCalculation() and private void weightCalculation() in the original class calculator.cs.
The function I need is like this:
When I execute the program and need to calculate the idealWeight and calories, the parent class calculator.cs will get the result from the formula contain in the sub-class, and ToString in the text box. That's why there are txtCalories and txtIdealWeight inside the calculator.cs.
So the question is how to get the results in the sub-class, and fill in the text boxes?
Guys, please help me with it as this is really important to me!!
Thank you all!!
Do you mean a virtual function? If so,
class Ancestor
{
public virtual int DoSomething()
{
// execute commands here.
// for now just throw exception.
throw new NotImplementedException();
}
}
class Derived_A : Ancestor
{
public override int DoSomething()
{
return 1 + 1;
}
}
class Derived_B : Ancestor
{
public override int DoSomething()
{
return 1 + 2;
}
}
This is ancestry, with virtual functions. For more on this:
Practical usage of virtual functions in c#
http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx
This type of code can also be done with interfaces. See http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx.
I want to display the information about whichever flight is selected in the listbox in textboxes next to it. My problem is I can't get my curFlight variable to work right gives me InvalidCastException was unhandled error and says When casting froim a number, the value must be a number less than infinity.
heres my form code
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 Reservations
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Flight curFlight;
Flight flight1 = new Flight("Cessna Citation X", "10:00AM", "Denver", 6, 2);
Flight flight2 = new Flight("Piper Mirage", "10:00PM", "Kansas City", 3, 2);
private void Form1_Load(object sender, EventArgs e)
{
MakeReservations();
DisplayFlights();
}
private void lstFlights_SelectedIndexChanged(object sender, EventArgs e)
{
curFlight = (Flight)lstFlights.SelectedItem;
txtDepart.Text = curFlight.DepartureTime;
txtDestination.Text = curFlight.Destination;
}
private void MakeReservations()
{
flight1.MakeReservation("Dill", 12);
flight1.MakeReservation("Deenda", 3);
flight1.MakeReservation("Schmanda", 11);
flight2.MakeReservation("Dill", 4);
flight2.MakeReservation("Deenda", 2);
}
private void DisplayFlights()
{
lstFlights.Items.Clear();
lstFlights.Items.Add(flight1.Plane);
lstFlights.Items.Add(flight2.Plane);
}
private void btnMakeReservation_Click(object sender, EventArgs e)
{
string name;
int seatNum;
name = txtCustomerName.Text;
seatNum = Convert.ToInt16(txtSeatNum.Text);
curFlight.MakeReservation(name, seatNum);
}
}
}
HERES THE CLASS CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reservations
{
class Flight
{
private string mPlane;
private string mDepartureTime;
private string mDestination;
private int mRows;
private int mSeats;
private string[] mSeatChart;
public Flight()
{
}
public Flight(string planeType, string departureTime, string destination, int numRows, int numSeatsPerRow)
{
this.Plane = planeType;
this.DepartureTime = departureTime;
this.Destination = destination;
this.Rows = numRows;
this.Seats = numSeatsPerRow;
// create the seat chart array
mSeatChart = new string[Rows * Seats];
for (int seat = 0; seat <= mSeatChart.GetUpperBound(0); seat++)
{
mSeatChart[seat] = "Open";
}
}
public string Plane
{
get { return mPlane; }
set { mPlane = value; }
}
public string DepartureTime
{
get { return mDepartureTime; }
set { mDepartureTime = value; }
}
public string Destination
{
get { return mDestination; }
set { mDestination = value; }
}
public int Rows
{
get { return mRows; }
set { mRows = value; }
}
public int Seats
{
get { return mSeats; }
set { mSeats = value; }
}
public string[] SeatChart
{
get { return mSeatChart; }
set { mSeatChart = value; }
}
public void MakeReservation(string name, int seat)
{
if (seat <= (Rows * Seats) && mSeatChart[seat - 1] == "Open")
{
mSeatChart[seat - 1] = name;
}
else
{
//let calling program know it didnt work.
}
}
public bool IsFull()
{
return false;
}
}
}
The reason you are getting the error is because you are assigning a string to the listbox and then trying to cast that string to a Flight Object
lstFlights.Items.Add(flight1.Plane); // Just say it is named "Plane 1"
lstFlights.Items.Add(flight2.Plane); // Just say it is named "Plane 2"
curFlight = (Flight)lstFlights.SelectedItem; // Now you are trying to convert "Plane 2" into a flight object which is incorrect
Try this instead
Add a Global List of type flights
List<Flight> flightList = new List<Flight>();
Flight flight1 = new Flight("Cessna Citation X", "10:00AM", "Denver", 6, 2);
Flight flight2 = new Flight("Piper Mirage", "10:00PM", "Kansas City", 3, 2);
in your form load add SetupFlights
private void Form1_Load(object sender, EventArgs e)
{
MakeReservations();
DisplayFlights();
SetupFlights(); // added this line
}
private void SetupFlights()
{
flightList.Add(flight1);
flightList.Add(flight2);
}
and your selected Index Changed should be something like this
private void lstFlights_SelectedIndexChanged(object sender, EventArgs e)
{
curFlight = flightList.FirstOrDefault(x => x.Plane == lstFlights.SelectedItem.ToString()); // Changed this line
txtDepart.Text = curFlight.DepartureTime;
txtDestination.Text = curFlight.Destination;
}
Although the answer by MVCKarl is more general, I'll show an easier way, which could suit in simple cases.
You could simply override ToString for the Flight class:
class Flight
{
//your code
public override string ToString()
{
//or anything you want to display
return this.Plane;
}
}
Then edit DisplayFlights method to add flights into the list:
private void DisplayFlights()
{
lstFlights.Items.Clear();
lstFlights.Items.Add(flight1);
lstFlights.Items.Add(flight2);
}
After this your lstFlights_SelectedIndexChanged would start working as expected:
private void lstFlights_SelectedIndexChanged(object sender, EventArgs e)
{
curFlight = (Flight)lstFlights.SelectedItem;
textBox1.Text = curFlight.DepartureTime;
textBox2.Text = curFlight.Destination;
}
I got a windows form application with a listbox that display content, I wanna be able to move the items from the listbox up and down, when a button is clicked. at the moment the items in the list box stored are in text file, which is loaded into configuration class when the application start. How would I move the items up/down and change the order in the text file?
my main application form code:
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;
using System.IO;
namespace company1
{
public partial class Form1 : Form
{
List<Configuration> lines = new List<Configuration>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
//Read in every line in the file
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
string[] array = new string[] { "\\n" };
string[] parts = new string[3];
parts = line.Split(array, StringSplitOptions.RemoveEmptyEntries);
lines.Add(new Configuration(parts[0], int.Parse(parts[1]), int.Parse(parts[2])));
line = reader.ReadLine();
}
}
listBox1.DataSource = lines;
listBox1.DisplayMember = "CompanyName";
}
}
}
the configuration class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace company1
{
class Configuration
{
string _CompanyName;
int _Employees;
int _Half;
public Configuration(string companyname, int number_of_Employees, int half)
{
_CompanyName = companyname;
_Employees = number_of_Employees;
_Half = half;
}
//program properties and validation
public string CompanyName
{
set
{
_CompanyName = value;
}
get
{
return _CompanyName;
}
}// End of levelname validation
//program properties and validation
public int EmployeesNumber
{
set
{
_Employees = value;
}
get
{
return _Employees;
}
}// End of levelname validation
//program properties and validation
public int Half
{
set
{
_Half = value;
}
get
{
return _Half;
}
}// End of levelname validation
}
}
any help appreciated, been trying for days to get it work.
// change the items in source list
var tmpLine = lines[10];
lines[10] = lines[9];
lines[9] = tmpLine;
// refresh datasource of listbox
listBox1.DataSource = null;
listBox1.DataSource = lines;
You could define an extension method for list to move items based on index:
public static class ExtensionClass
{
public static void Move<T>(this List<T> list, int index1, bool moveDown = true)
{
if (moveDown)
{
T temp = list[index1];
list[index1] = list[index1 + 1];
list[index1 + 1] = temp;
}
else
{
T temp = list[index1];
list[index1] = list[index1 - 1];
list[index1 - 1] = temp;
}
}
}
Then in Code you can:
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("Original List");
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 2 Down");
list.Move(2);
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 3 Up");
list.Move(3, false);
foreach (int i in list)
{
Console.Write(i + ",");
}
Output will be:
Original List
1,2,3,4,5,6,7,
Move Index 2 Down
1,2,4,3,5,6,7,
Move Index 3 Up
1,2,3,4,5,6,7,