Edit Delete and save in stream reader c# visual studio 2010 - c#

I am new to programming and I need your help please.I am using C# Visual Studio 2010 and I need to be able to read from a file and display the Data in to the relevant text boxes.
The text file is a list of Football Teams and I have to Display, Edit, Delete and save the file. I have done some research and used YouTube to create programs that use Stream Readers but they don't do what I want them to do. I understand how stream readers reads the data but I am having difficulties in Displaying the data LINE BY LINE in the relevant boxes IE: Team Name, Team Manager, Team Stadium etc. I have made the class for Team which is listed below along with the Forms Code that i am having problems with. Any Help would be much appreciated.
My Class: Team
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace The_F.A__Soft130_Assignment_
{
class Team
{
private string Name;
private string League;
private string Manager;
private string Nickname;
private string Stadium;
private int Position;
private int Points;
private int GamesPlayed;
private int GoalDiff;
private string Logo;
private int NumberPlayers;
// constructor
public Team(string theName, string theLeague, string theManager,
string theNickname, string theStadium, string thePosition,
string thePoints, string theGamesPlayed,string theGoalDiff,
string theLogo, string theNumberPlayers)
{
Name = theName;
League = theLeague;
Manager = theManager;
Nickname = theNickname;
Stadium = theStadium;
setPosition(thePosition);
setPoints(thePoints);
setGamesPlayed(theGamesPlayed);
setGoalDiff(theGoalDiff);
Logo = theLogo;
setNumberPlayers(theNumberPlayers);
}
public Team(string theName, string theLeague, string theManager,
string theNickname, string theStadium,
string theLogo, string theNumberPlayers)
{
Name = theName;
League = theLeague;
Manager = theManager;
Nickname = theNickname;
Stadium = theStadium;
Logo = theLogo;
setNumberPlayers(theNumberPlayers);
}
//The getter methods
public string getName()
{
return Name;
}
public string getLeague()
{
return League;
}
public string getManager()
{
return Manager;
}
public string getNickname()
{
return Nickname;
}
public string getStadium()
{
return Stadium;
}
public int getPosition()
{
return Position;
}
public int getPoints()
{
return Points;
}
public int getGamesPlayed()
{
return GamesPlayed;
}
public int getGoalDiff()
{
return GoalDiff;
}
public string getLogo()
{
return Logo;
}
public int getNumberPlayers()
{
return NumberPlayers;
}
// all the Class setter methods
public void setName(string theName)
{
Name = theName;
}
public void setLeague(string theLeague)
{
League = theLeague;
}
public void setManager(string theManager)
{
Manager = theManager;
}
public void setNickname(string theNickname)
{
Nickname = theNickname;
}
public void setStadium(string theStadium)
{
Stadium = theStadium;
}
public void setPosition(string thePosition)
{
try
{
Position = Convert.ToInt32(thePosition);
}
catch (FormatException e)
{
System.Windows.Forms.MessageBox.Show("Error:" + e.Message
+ "Please input a valid of number");
}
}
public void setPoints(string thePoints)
{
try
{
Points = Convert.ToInt32(thePoints);
}
catch (FormatException e)
{
System.Windows.Forms.MessageBox.Show("Error:" + e.Message
+ "Please input a valid number");
}
}
public void setGamesPlayed(string theGamesPlayed)
{
try
{
GamesPlayed = Convert.ToInt32(theGamesPlayed);
}
catch (FormatException e)
{
System.Windows.Forms.MessageBox.Show("Error:" + e.Message
+ "Please in put valid number");
}
}
public void setGoalDiff(string theGoalDiff)
{
try
{
GoalDiff = Convert.ToInt32(theGoalDiff);
}
catch (FormatException e)
{
System.Windows.Forms.MessageBox.Show("Error:" + e.Message
+ "Please input valid number");
}
}
public void setLogo(string theLogo)
{
Logo = theLogo;
}
public void setNumberPlayers(string theNumberPlayers)
{
try
{
NumberPlayers = Convert.ToInt32(theNumberPlayers);
}
catch (FormatException e)
{
System.Windows.Forms.MessageBox.Show("Error:" + e.Message
+ "Please input Valid Number");
}
}
}
}
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;
using System.Collections;
using System.Text.RegularExpressions;
namespace The_F.A__Soft130_Assignment_
{
public partial class frmEditTeam : Form
{
public frmEditTeam()
{
InitializationComponent();
}
private void InitializationComponent()
{
throw new NotImplementedException();
}
//EDIT Team --- EDIT Team --- EDIT Team --- EDIT Team --- EDIT Team --- EDIT
private void btnEdit_Click(object sender, EventArgs e)
{
bool allInputOK = false;
League whichLeague = (League)frmFA.Leagues[frmFA.leagueSelected];
//get inputs - Team ORDER = Author Title Year Copies Isbn
string tempName = txtEditTeamName.Text;
string tempLeague = txtEditTeamLeague.Text;
string tempManager = txtEditTeamManager.Text;
string tempNickname = txtEditTeamNickname.Text;
string tempStadium = txtEditTeamStadium.Text;
string templogo = txtEditTeamlogo.Text;
int tempNoOfPlayers = txtEditTeamNoofPlayers.Text;
int tempPosition;
int tempPoints;
int tempGamePlayed;
int tempGoalDiff;
//final validation check
allInputOK = Utilities.notNullTextBox(txtEditTeamName, "Team name") && Utilities.notNullTextBox(txtEditTeamLeague, "Team league")
&& Utilities.notNullTextBox(txtEditTeamManager, "Team manager") && Utilities.notNullTextBox(txtEditTeamNickname, "Team Nickname")
&& Utilities.notNullTextBox(txtEditTeamStadium, "Team stadium") && Utilities.notNullTextBox(txtEditTeamlogo, "Team logo")
&& Utilities.notNullTextBox(txtEditTeamNoofPlayers, "Team number of players")
&& Utilities.validNumber(txtTeamPosition, "The Teams Position")
&& Utilities.validNumber(txtTeamPoints, " The Teams Points") && Utilities.validNumber(txtTeamGamesPlayed, "Games Played")
&& Utilities.validNumber(txtTeamGoalDiff, " The Goal Differance");
//create Team if all ok
if (allInputOK)
{
Team temp = new Team(tempName, tempLeague, tempManager, tempNickname, tempStadium, tempPosition, tempPoints, tempGamePlayed, tempGoalDiff, templogo, tempNoOfPlayers);
whichLeague.replaceTeam(whichLeague.getleagueAllTeams(), temp,frmFA.teamselected);
Utilities.WriteAllLeagueTeams(frmFA.inputDataFile1, frmFA.Leagues);// update file
MessageBox.Show("Success: Team " + tempName + " edited in " + whichLeague.getleagueName());//finish up
resetForm();
}
}
//LOAD Team DETAILS --- LOAD Team DETAILS --- LOAD Team DETAILS --- LOAD Team DETAILS ---
private void getTeamDetails()
{
//convert this to the corrcet team reference
//int selected team = frmFA.Team Selected;
int selectedTeam = frmFA.teamSelected;
int selectedLeague = frmFA.leagueSelected;
//GET Team
//starting out with access to all the leagues
ArrayList allLeagues = frmFA.Leagues;
//narrow it down to which League you want
League currentLeague = (League)allLeagues[selectedLeague];
//narrow it down to which Team you want form that League
Team currentTeam = (Team)currentLeague.getleagueAllTeams()[selectedTeam];
//get Team details
txtEditTeamName.Text = currentTeam.getName();
txtEditTeamManager = currentTeam.getManager();
txtEditTeamStadium.Text = currentTeam.getStadium();
txtEditTeamNoofPlayers.Text = currentTeam.getNoOfPlayers();
txtEditTeamLeague.Text = currentTeam.getTeamLeague();
txtEditTeamLogo.Text = currentTeam.getTeamlogo();
}
// event procedure
private void btnHomeAdd_Team_Click(object sender, EventArgs e)
{
frmFA form = new frmFA(); form.Show();
this.Hide();
}
private void btnRefreshClick(object sender, EventArgs e)
{
Refresh();
}
private void btnEditTeamUpdate_Click(object sender, EventArgs e)
{
frmEditTeam form = new frmEditTeam();
form.Show();
this.Hide();
}
private void txtEditTeamName_TextChanged(object sender, EventArgs e)
{
getTeamName();
}
private void txtEditTeamLeague_TextChanged(object sender, EventArgs e)
{
getTeamLeague();
}
private void txtEditTeamManager_TextChanged(object sender, EventArgs e)
{
getTeamManager();
}
private void txtEditTeamNickName_TextChanged(object sender, EventArgs e)
{
getTeamNickName();
}
private void txtEditTeamStadium_TextChanged(object sender, EventArgs e)
{
getTeamStadium();
}
private void txtEditTeamLogo_TextChanged(object sender, EventArgs e)
{
getLogo();
}
private void txtEditTeamNoofPlayers_TextChanged(object sender, EventArgs e)
{
getNoOfPlayers();
}
private void txtEditTeamNickname_TextChanged_1(object sender, EventArgs e)
{
getTeamNickname();
}
private void resetForm()
{
txtName.Text = "";
txtLeague.Text = "";
txtManager.Text = "";
txtNickname.Text = "";
txtStadium.Text = "";
txtPosition.Text = "";
txtPoints.Points = "";
txtGamesPlayed.GamesPlayed = "";
txtGoalDiff.GoalDiff = "";
txtLogo.Logo = "";
txtNoOfPlayers = "";
txtName.Focus();
}
private void btnEditTeamUpdate_Click_1(object sender, EventArgs e)
{
}
private void frmEditTeam_Load(object sender, EventArgs e)
{
}
}
}

This is just a basic outline, but what I'd do,
use a StreamReader to load your data in
use your own classes to manage your data while the application is running
use a StreamWriter when you decide you want to save your data, you should probably save in response to some sort of button.

Related

Cannot get IF statements to update TextBlock from ComboBox Selection C#

I am trying to get a return back to the main program but it has to change on the ComboBox change. No matter what it is returning whatever the String is set to at the top of the class. If I change the result = ""; to result = "Test"; it will display Test in the TextBox I am trying to update. But it won't get anything from the IF statements.
Thanks for the help!
MAIN PROGRAM
namespace VTCPT
{
/// <summary>
///
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
if (String.IsNullOrEmpty(display.finalResult()))
{ shortFormCodec.Text = ".."; }
else { shortFormCodec.Text = display.finalResult(); }
}
private void updateShortForm(object sender, SelectionChangedEventArgs e)
{
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void fsSiteBuild_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void updateSiteBuild(object sender, TextChangedEventArgs e)
{
int index = fsRoomDesig.Text.IndexOf(".");
if (index > 0)
{ fsSiteBuild.Text = fsRoomDesig.Text.Substring(0, index); }
else { fsSiteBuild.Text = ".."; }
}
private void vtcSystemName_SelectionChanged(object sender, RoutedEventArgs e)
{
}
}
}
updateVTCShortCode CLASS
namespace VTCPT
{
class updateVTCShortCode
{
String result = ""; //////ALWAYS RESULTS ONLY IN WHAT IS HERE
public void mergeShortCode(String longFormCodec)
{
if (longFormCodec == "Cisco SX80")
{
String sendShortForm = "SX80";
result = "V-T" + sendShortForm;
}
if (longFormCodec == "Cisco Webex Codec Plus")
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
if (longFormCodec == "Cisco Webex Codec Pro")
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
}
public String finalResult()
{ return result; }
}
}
You are not doing the string comparisons correctly. You need to use .equals() for strings.
You need to replace all the string comparisons where you are using == to .equals() and it will work:
namespace VTCPT
{
class updateVTCShortCode
{
String result = ""; //////ALWAYS RESULTS ONLY IN WHAT IS HERE
public void mergeShortCode(String longFormCodec)
{
if (longFormCodec.equals("Cisco SX80"))
{
String sendShortForm = "SX80";
result = "V-T" + sendShortForm;
}
if (longFormCodec.equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
if (longFormCodec.equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
}
public String finalResult()
{ return result; }
}
}

MessageBox doesn't show the variable

I have a list variable and I created an iterator for it to print out its content. It's working in the console application but when i try to do it using windows form(gui) it doesn't work
PROGRAM.CS
namespace gui
{
static class Program
{
public class studentdata
{
public string id, name, password, academicyear, finishedcourseslist, ipcourseslist;
public int noCoursesF, noCoursesIP;
public List<string> coursesF;
public List<string> coursesIP;
public studentdata()
{
id = "2015123";
password = "Student";
coursesF = new List<string>();
coursesIP = new List<string>();
}
public studentdata(string ID, string NAME, string PASSWORD)
{
id = ID;
}
**public void view_finished_courses()
{
List<string> finished = coursesF;
foreach (string n in finished)
{
finishedcourseslist += n;
}
MessageBox.Show(finishedcourseslist, "Finished courses");
}
public void view_ip_courses()
{
List<string> progress = coursesIP;
foreach (string m in progress)
{
ipcourseslist += m;
}
MessageBox.Show(ipcourseslist, "Finished courses");
}**
}
public class Admin
{
public string name, password;
public Admin()
{
name = "Admin";
password = "Admin";
}
}
//functionssssss
internal static studentdata studentSearch(string IDsearch)
{
FileStream FS = new FileStream("Students.txt", FileMode.Open);
StreamReader SR = new StreamReader(FS);
studentdata std = new studentdata();
while (SR.Peek() != -1)
{
string z = SR.ReadLine();
String[] Fields;
Fields = z.Split(',');
if (IDsearch.CompareTo(Fields[0]) == 0)
{
std.id = Fields[0];
std.password = Fields[1];
std.name = Fields[2];
std.noCoursesF = int.Parse(Fields[3]);
int currentField = 4;
for (int course = 0; course < std.noCoursesF; course++)
{
std.coursesF.Add(Fields[currentField]);
currentField++;
}
std.noCoursesIP = int.Parse(Fields[currentField]);
currentField++;
for (int course = 0; course < std.noCoursesIP; course++)
{
std.coursesIP.Add(Fields[currentField]);
currentField++;
}
std.academicyear = Fields[currentField];
SR.Close();
return std;
}
else continue;
}
SR.Close();
studentdata araf = new studentdata();
return araf;
}
}
FORM.CS
namespace gui
{
public partial class Form3 : Form
{
Program.studentdata student = new Program.studentdata();
public Form3()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
student.view_finished_courses();
}
private void button6_Click(object sender, EventArgs e)
{
student.view_ip_courses();
}
}
}
The output is an empty message box, I don't know why variable isn't added.
Replace messagebox line with
MessageBox.Show(string.Join(",", coursesF.ToArray()), "Finished courses");
It seems like your code is incomplete. Nowhere in the code which gets executed after you clicked button4 you are adding items to coursesF. It seems that you are adding items in this line: std.coursesF.Add(Fields[currentField]);
This line is in your function studentSearch(IDsearch), the function never gets called.
In this function you got a string z in which all the data of a student is saved (string z = SR.ReadLine()). You must somehow fill this string z. You can use a TextBox in your form and pass the value into the string, use a string from a text file or use the console input(see here: Get input from console into a form).
As you can see the issue is not a one line fix.

How to find items in a ListBox?

I am creating an application where I have a ListBox which has items that are read in from a text file using StreamReader. I have created a search form but I'm not sure what to do next. Can anyone give me some suggestions please? Here is my code:
My code for the ListBox (sorry it's so long)
public partial class frmSwitches : Form
{
public static ArrayList switches = new ArrayList();
public static frmSwitches frmkeepSwitches = null;
public static string inputDataFile = "LeckySafe.txt";
const int numSwitchItems = 6;
public frmSwitches()
{
InitializeComponent();
frmkeepSwitches = this;
}
private void btnDevices_Click(object sender, EventArgs e)
{
frmDevices tempDevices = new frmDevices();
tempDevices.Show();
frmkeepSwitches.Hide();
}
private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
{
try
{
dataIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
+ notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
+ e.Message);
return false;
}
}
private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
{
string nextLine;
int numDataItems = nextSwitchData.Count();
for (int i = 0; i < numDataItems; i++)
{
try
{
nextLine = inNext.ReadLine();
if (nextLine != null)
nextSwitchData[i] = nextLine;
else
{
return false;
}
}
catch (Exception e)
{
MessageBox.Show("ERROR Reading from file.\n" + e.Message);
return false;
}
}
return true;
}
private void readSwitches()
{
StreamReader inSwitches = null;
Switch tempSwitch;
bool anyMoreSwitches = false;
string[] switchData = new string[numSwitchItems];
if (fileOpenForReadOK(inputDataFile, ref inSwitches))
{
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
while (anyMoreSwitches == true)
{
tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);
switches.Add(tempSwitch);
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
}
}
if (inSwitches != null) inSwitches.Close();
}
public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
{
try
{
dataOut = new StreamWriter(writeFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when writing data out)" +
"- File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when writing data out)" +
"- Operation failed.\n" + e.Message);
return false;
}
}
public static void writeSwitches()
{
StreamWriter outputSwitches = null;
if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
{
foreach (Switch currSwitch in switches)
{
outputSwitches.WriteLine(currSwitch.getSerialNo());
outputSwitches.WriteLine(currSwitch.getType());
outputSwitches.WriteLine(currSwitch.getInsDate());
outputSwitches.WriteLine(currSwitch.getElecTest());
outputSwitches.WriteLine(currSwitch.getPatId());
outputSwitches.WriteLine(currSwitch.getNumDevice());
}
outputSwitches.Close();
}
if (outputSwitches != null) outputSwitches.Close();
}
private void showListOfSwitches()
{
lstSwitch.Items.Clear();
foreach (Switch b in switches)
lstSwitch.Items.Add(b.getSerialNo()
+ b.getType() + b.getInsDate()
+ b.getElecTest() + b.getPatId() + b.getNumDevice());
}
My code for the search form:
private void btnSearch_Click(object sender, EventArgs e)
{
frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
tempSearchSwitch.Show();
frmkeepSwitches.Hide();
}
If using a List<T> and lambda is not possible for you then go no farther.
Here I use a List<T> for the data source of a ListBox and mocked up data as where the data comes from is not important but here I am focusing on searching on a property within a class where a select is used to index the items then the where searches in this case) for a specific item, if found the index is used to move to the item. No code present for if not located as this is easy for you to do if the code here is something that is doable for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ListBoxSearch_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var results =
((List<Item>)ListBox1.DataSource)
.Select((data, index) => new
{ Text = data.SerialNumber, Index = index })
.Where((data) => data.Text == "BB1").FirstOrDefault();
if (results != null)
{
ListBox1.SelectedIndex = results.Index;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Item>() {
new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
};
ListBox1.DisplayMember = "DisplayText";
ListBox1.DataSource = items;
}
}
/// <summary>
/// Should be in it's own class file
/// but done here to keep code together
/// </summary>
public class Item
{
public string SerialNumber { get; set; }
public string Type { get; set; }
public int Identifier { get; set; }
public string DisplayText
{
get
{
return SerialNumber + " " + this.Type;
}
}
}
}

Windows Form Not Returning Correct Value from Public Method

I have three classes, code provided below.
Network - Add and Remove Phone, Process Calls
Phone1 and Phone2 can call each other when added to the network.
But I am having issue when I am connecting both phone to the network and trying to call phone1 to phone2, it is keep giving me "receiver busy". I have tried to do little debugging and read status of phone2 when calling from phone1 but it returns an empty string (Which should actually return "A", when it is added to the network).
Any help would much appreciated.
-----Networks Class------------------
namespace Demo
{
public partial class network : Form
{
phone1 p1 = new phone1();
phone2 p2 = new phone2();
public network()
{
InitializeComponent();
}
public Boolean numberValidator(int number)
{
Boolean exist = false;
if (comboBox2.Items.Equals(number))
{
exist = true;
}
return exist;
}
public void processCall(int rNumber)
{
if (!numberValidator(rNumber))
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Not connected";
//MessageBox.Show(p2.returnPhoenStatus());
}
else
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call in progress";
p2.receiveCall(1);
p1.setStatus("Busy");
/*
if (p2.btnCallPressStatus())
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call initiated";
}*/
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
p1.Show();
comboBox2.Items.Add(1);
p1.setStatus("A");
}
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
}
}
}
----------Phone1 Class---------
namespace Demo
{
public partial class phone1 : Form
{
public phone1()
{
InitializeComponent();
}
string status;
public void setStatus(string Status)
{
status = Status;
}
public string returnStatus()
{
return status;
}
public void receiveCall(int callerNumber)
{
setStatus("Busy");
btnCall.Text = "Answer";
textBox1.Text = "Phone " + callerNumber + " Calling.";
}
public void makeCall(int number)
{
phone2 p2 = new phone2();
network net = new network();
MessageBox.Show(p2.returnStatus()); // this line not returing status of phone2
if (p2.returnStatus() == "A")
{
net.processCall(number);
}
else
{
textBox1.Text = "Receiver Busy";
}
}
public TextBox TextBox1
{
get
{
return textBox1;
}
}
private void btnCall_Click(object sender, EventArgs e)
{
string number = textBox1.Text;
int numberInt = Convert.ToInt16(number);
makeCall(numberInt);
}
string phoneNo = "";
private void btn2_Click(object sender, EventArgs e)
{
phoneNo = phoneNo + btn2.Text;
textBox1.Text = phoneNo;
}
}
}
-------------phone2 Class--------------
namespace Demo
{
public partial class phone2 : phone1
{
public phone2()
{
InitializeComponent();
}
}
}
I think you are setting the status of P1 both the times. Check this if condition in button1_Click method in network class. The setStatus should be for P2.
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
Piyush has the right answer, but I thought I'd add this answer as a handy hint to avoid this kind of error.
Try writing your button1_Click method like this:
private void button1_Click(object sender, EventArgs e)
{
var i = comboBox1.SelectedIndex;
var p = (new [] { p1, p2 })[i]; // Or `var p = i == 0 ? p1 : p2;`
p.Show();
comboBox2.Items.Add(i + 1);
p.setStatus("A");
}
This way you avoid the code duplication and the mistyping that occurred.

display information about an object selected in a listbox in textboxes

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

Categories