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.
Related
I'm new to C# and I'm trying to copy and rename an image file(.png). The copying process is working. But the copy should be named "OUTPUT.png" and not use the old name or any parts of it.
Important edit:
The old/original file name is not known, because it is created randomly.
I'd appreciate your help, thoughts, etc.
private void Form1_Load(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\booth\Documents\190604_avee_1.4\Files\Snapshots";
string backupDir = #"C:\Users\booth\Documents\190604_avee_1.4\Files";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
File.Copy(#"C:\Users\booth\Documents\190604_avee_1.4\Files\Snapshots\*.png", #"C:\Users\booth\Documents\190604_avee_1.4\Files\OUTPUT.png");
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
Is it possible that your Copy call should be using the fName var that you create the line before? Trying to copy a wildcard filename when you have a var with the file name in it seems impractical. So something like File.Copy(#"[insert path]\"+fName, ...) should work, right?
Now if your purpose is to copy the .png ones from the corresponding folder to the other folder and then delete the images, this code will do the trick.
using System;
using System.IO;
using System.Windows.Forms;
namespace Udemyvericekme
{
public partial class opera : Form
{
public opera()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\Ebubekir\Desktop\resimler\";
string backupDir = #"C:\Users\Ebubekir\Desktop\bekrabackup\";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
try
{
File.Copy(f, backupDir + fName);
}
catch
{
}
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
}
}
You can use this code:
using System;
using System.IO;
using System.Windows.Forms;
namespace Udemyvericekme
{
public partial class opera : Form
{
public opera()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\Ebubekir\Desktop\resimler\";
string backupDir = #"C:\Users\Ebubekir\Desktop\bekrabackup\";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
try
{
File.Copy(f, backupDir + "OUTPUT" + fName);
}
catch
{
}
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
}
}
File.Copy(f, backupDir + "OUTPUT" + fName);
You just change it here
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.
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;
}
}
}
}
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.
g'day guys,
i have a small error with my program where when i try to save to file an error occurs which says "A required privilege is not held by the client." I not sure how to fix this as i am running it off of my laptop which only i use and unless i have set up administrator status correctly i dont know what is going on.
I posted my code below just to be sure
Cheers.
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.IO.Ports;
using System.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void addlistitemcallback(string value);
public static string inputdata;
public static int MaximumSpeed, maximumRiderInput, RiderInput, Time, CurrentSpeed, DistanceTravelled, MaximumMotorOutput, MotorOutput, InputSpeed;
public static string SaveDataString;
public Thread Serial;
public static SerialPort SerialData;
public static string[] portlist = SerialPort.GetPortNames();
public static string[] SaveData = new string[4];
public static string directory = "C:\\";
public Form1()
{
Serial = new Thread(ReadData);
InitializeComponent();
int Count = 0;
for (Count = 0; Count < portlist.Length; Count++)
{
ComPortCombo.Items.Add(portlist[Count]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void StartDataButton_Click(object sender, EventArgs e)
{
SerialData = new SerialPort(ComPortCombo.Text, 19200, Parity.None, 8, StopBits.One);
SerialData.Open();
SerialData.WriteLine("P");
Serial.Start();
StartDataButton.Enabled = false;
EndDataButton.Enabled = true;
ComPortCombo.Enabled = false;
CurrentSpeed = 0;
MaximumSpeed = 0;
Time = 0;
DistanceTravelled = 0;
MotorOutput = 0;
RiderInput = 0;
SaveData[0] = "";
SaveData[1] = "";
SaveData[2] = "";
SaveData[3] = "";
SaveDataButton.Enabled = false;
if (SerialData.IsOpen)
{
ComPortStatusLabel.Text = "OPEN";
SerialData.NewLine = "/n";
SerialData.WriteLine("0");
SerialData.WriteLine("/n");
}
}
private void EndDataButton_Click(object sender, EventArgs e)
{
SerialData.Close();
SaveDataButton.Enabled = true;
//SerialData.WriteLine("1");
//SerialData.WriteLine("0");
if (!SerialData.IsOpen)
{
ComPortStatusLabel.Text = "CLOSED";
}
int i = 0;
for (i = 0; i < 4; i++)
{
if (i == 0)
{
SaveDataString = "MaximumSpeed during the Ride was = " + Convert.ToString(MaximumSpeed) + "m/h";
SaveData[i] = SaveDataString;
}
if (i == 1)
{
SaveDataString = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "m";
SaveData[i] = SaveDataString;
}
if (i == 2)
{
SaveDataString = "Maximum Rider Input Power = " + Convert.ToString(maximumRiderInput) + "Watts";
SaveData[i] = SaveDataString;
}
if (i == 3)
{
SaveDataString = "Maximum Motor Output Power = " + Convert.ToString(MaximumMotorOutput) + "Watts";
SaveData[i] = SaveDataString;
}
}
}
private void SaveDataButton_Click(object sender, EventArgs e)
{
//File.WriteAllBytes(directory + "image" + imageNO + ".txt", ); //saves the file to Disk
File.WriteAllLines("C:\\" + "BikeData.txt", SaveData);
}
public void updateSpeedtextbox(string value)
{
if (SpeedTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateSpeedtextbox);
Invoke(d, new object[] { value });
}
else
{
SpeedTextBox.Text = value;
}
}
public void updatePowertextbox(string value)
{
if (RiderInputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updatePowertextbox);
Invoke(d, new object[] { value });
}
else
{
RiderInputTextBox.Text = value;
}
}
public void updateDistancetextbox(string value)
{
if (DistanceTravelledTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateDistancetextbox);
Invoke(d, new object[] { value });
}
else
{
DistanceTravelledTextBox.Text = value;
}
}
public void updateMotortextbox(string value)
{
if (MotorOutputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateMotortextbox);
Invoke(d, new object[] { value });
}
else
{
MotorOutputTextBox.Text = value;
}
}
public void ReadData()
{
int counter = 0;
while (SerialData.IsOpen)
{
if (counter == 0)
{
try
{
InputSpeed = Convert.ToInt16(SerialData.ReadChar());
if (CurrentSpeed > MaximumSpeed)
{
MaximumSpeed = CurrentSpeed;
}
updateSpeedtextbox("Current Wheel Speed = " + Convert.ToString(InputSpeed) + "Km/h");
DistanceTravelled = DistanceTravelled + (Convert.ToInt16(InputSpeed) * Time);
updateDistancetextbox("Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km");
}
catch (Exception) { }
}
if (counter == 1)
{
try
{
RiderInput = Convert.ToInt16(SerialData.ReadChar());
if (RiderInput > maximumRiderInput)
{
maximumRiderInput = RiderInput;
}
updatePowertextbox("Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts");
}
catch (Exception) { }
}
if (counter == 2)
{
try
{
MotorOutput = Convert.ToInt16(SerialData.ReadChar());
if (MotorOutput > MaximumMotorOutput)
{
MaximumMotorOutput = MotorOutput;
}
updateMotortextbox("Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts");
}
catch (Exception) { }
}
counter++;
if (counter == 3)
{
counter = 0;
}
}
}
private void Form1_Closed(object sender, EventArgs e)
{
if (SerialData.IsOpen)
{
SerialData.Close();
}
}
private void ComPortCombo_SelectedIndexChanged(object sender, EventArgs e)
{
StartDataButton.Enabled = true;
}
private void DistanceTravelledTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
You probably don't have write access to C:\. Try changing the save path to "C:\Users\{YouName}\Documents\BikeData.txt" instead.
Or start Visual Studio with administrative privileges by right clicking on its icon and choosing "Run as Administrator"
File.WriteAllLines("C:\" + "BikeData.txt", SaveData);
File.WriteAllLine(string,string[]), through "SecurityException" when user does not have rights to write in a particular directrory or drive so you have to give write permission, refer this link File.WriteAllLines