private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
this.Close();
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
private void button3_Click(object sender, EventArgs e)
{
File.AppendAllText("student.txt", "\r\n" + txtStudNum.Text + ", " +
txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
}
private void button4_Click(object sender, EventArgs e)
{
}
I want to calculate the average for txtModMark from the textfile once all the values have been entered. It will go under button 4 so when I click it, it calculates. I need to know how to skip the first few columns per row and get to the last column to perform the average calculation.
What's the point in reading from file then parse it and then convert to INT and then calculate average when you can do it directly using s List<int> like below:
declare a List<int> in your Form
List<int> marks = new List<int>();
Store the marks in button click event
private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
marks.Add(Convert.ToInt32(txtModMark.Text)); //add to list
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
In button4 click event calculate the average
private void button4_Click(object sender, EventArgs e)
{
int totalmarks = 0;
foreach(int m in marks)
totalmarks += m;
MessageBox.Show("Average Is: " + totalmarks / marks.Count);
}
Related
I am making a windows form application that takes various game entries (title,genre,price) and then stores them in an array with a maximum of four entries.
The error I am having is that if there are no values entered in my text boxes, I want a message box to appear to force the user to enter values. This happens.
The problem is that after this, it does not give the user another try. It just stops the program. I have tried using a try catch statement to do this but I am not quite sure how to use this. Would this be the correct solution?
namespace gameForm
{
public partial class gameEntryForm : Form
{
public gameEntryForm()
{
InitializeComponent();
}
struct Game
{
public string Title;
public string Genre;
public decimal Price;
}
static Game[] aNewGame = new Game[4]; //max size of the array is 4
static int newGameEntryIndex = 1;
private void gameEntryForm_Load(object sender, EventArgs e)
{
aNewGame[0].Title = "golf tour"; //this is a game already stored in the database
aNewGame[0].Genre = "sports";
aNewGame[0].Price = 1.99m;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
}
//catch()
//{
//}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
private void btnShow_Click(object sender, EventArgs e)
{
rtbShow.Text = "Game Details \n\nGame 1 \n" + aNewGame[0].Title + "\n" + aNewGame[0].Genre + "\n" + aNewGame[0].Price + "\n\n" + "Game 2 \n" + aNewGame[1].Title + "\n" + aNewGame[1].Genre + "\n" + aNewGame[1].Price + "\n\n" + "Game 3 \n" + aNewGame[2].Title + "\n" + aNewGame[2].Genre + "\n" + aNewGame[2].Price + "\n\n" + "Game 4 \n" + aNewGame[3].Title + "\n" + aNewGame[3].Genre + "\n" + aNewGame[3].Price; ;
}
//clears the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
rtbShow.Clear();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Add a return, no try/catch required:
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
return; // Exit current function
}
Try/catch is for when you have exceptions.
Try-Catch is of no use to you.
What you should do is in the btnSave_Click method return when the textboxes are not populated:
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text)
{
MessageBox.Show("Please enter a game genre, game title and game price.");
return;
}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
...
There is another solution you could do. Only activate the Save-button if all three textboxes has values in them.
Something like:
private void ValidateGameData(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text))
{
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
tbGenre.TextChanged += ValidateGameData;
tbTitle.TextChanged += ValidateGameData;
tbPrice.TextChanged += ValidateGameData;
In your code for btnSave_Click you are testing the value of the various TextBoxes and displaying a message if they are NULL or empty.
However, you continue execution of your code even if they are NULL or empty.
You should stop processing more code if the conditions fail so that you don't try to use the NULL\empty values.
Something like:
private void btnSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
else if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
else if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
else
{
// You forgot to create the new game at this index
aNewGame[newGameEntryIndex] = new Game();
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
}
I've also added a line:
aNewGame[newGameEntryIndex] = new Game();
As I couldn't see anywhere that you created the new Game object before trying to set it's properties.
This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
Basicly I'm writing a fake malware, which will write in a .txt the Session username of the person which clicked on it. The problem is that when someone execute it will erase the previous lines.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "Fake Malware";
}
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("Link to a warning message on click, nothing important.");
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
I think what you are looking for is AppendAllText:
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", "Wow it worked :)");
Here is the fix
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("#");
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
}
We have a project to do a program to add and remove universities and had five universities inside our .txt file to show them in our ComboBox.
But it doesn`t work and shows this error:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Note: It's a Windows Form.
So here's the code:
public partial class Form1 : Form
{
university[] univ = new university[10];
struct university
{
public string uni;
public string prov;
public string city;
public string population;
public string programs;
public string tuition;
public string residence;
}
public Form1()
{
InitializeComponent();
}
private void pictureBox4_Click(object sender, EventArgs e)
{
MessageBox.Show("If you want to check the infomation, click on the combo box and then choose the University of your choice.\n- Click the black button to add a university to the list after filling in everything. \n- Click the red button to remove a university after selecting it.");
}
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("Universities.txt"); // object
String line;
try
{
for (int i = 0; i < univ.Length; i++)
{
line = sr.ReadLine();
string[] sPlit = line.Split(',');
univ[i].uni = sPlit[0];
univ[i].prov = sPlit[1];
univ[i].city = sPlit[2];
univ[i].population = sPlit[3];
univ[i].programs = sPlit[4];
univ[i].tuition = sPlit[5];
univ[i].residence = sPlit[6];
comboBox1.Items.Add(univ[i].uni);
}
sr.Close();
}
catch (Exception p) //catches errors
{
Console.WriteLine("Exception: " + p.Message);
}
finally //final statement before closing
{
Console.WriteLine("Executing finally block.");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._1;
listBox1.Items.Add("Province: " + univ[0].prov);
listBox1.Items.Add("City: " + univ[0].city);
listBox1.Items.Add("Population: " + univ[0].population);
listBox1.Items.Add("Programs: " + univ[0].programs);
listBox1.Items.Add("Tuition: $" + univ[0].tuition);
listBox1.Items.Add("Residence: $" + univ[0].residence);
}
else if (comboBox1.SelectedIndex == 1)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._2;
listBox1.Items.Add("Province: " + univ[1].prov);
listBox1.Items.Add("City: " + univ[1].city);
listBox1.Items.Add("Population: " + univ[1].population);
listBox1.Items.Add("Programs: " + univ[1].programs);
listBox1.Items.Add("Tuition: $" + univ[1].tuition);
listBox1.Items.Add("Residence: $" + univ[1].residence);
}
else if (comboBox1.SelectedIndex == 2)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._3;
listBox1.Items.Add("Province: " + univ[2].prov);
listBox1.Items.Add("City: " + univ[2].city);
listBox1.Items.Add("Population: " + univ[2].population);
listBox1.Items.Add("Programs: " + univ[2].programs);
listBox1.Items.Add("Tuition: $" + univ[2].tuition);
listBox1.Items.Add("Residence: $" + univ[2].residence);
}
else if (comboBox1.SelectedIndex == 3)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._4;
listBox1.Items.Add("Province: " + univ[3].prov);
listBox1.Items.Add("City: " + univ[3].city);
listBox1.Items.Add("Population: " + univ[3].population);
listBox1.Items.Add("Programs: " + univ[3].programs);
listBox1.Items.Add("Tuition: $" + univ[3].tuition);
listBox1.Items.Add("Residence: $" + univ[3].residence);
}
else if (comboBox1.SelectedIndex == 4)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._5;
listBox1.Items.Add("Province: " + univ[4].prov);
listBox1.Items.Add("City: " + univ[4].city);
listBox1.Items.Add("Population: " + univ[4].population);
listBox1.Items.Add("Programs: " + univ[4].programs);
listBox1.Items.Add("Tuition: $" + univ[4].tuition);
listBox1.Items.Add("Residence: $" + univ[4].residence);
}
else
{
pictureBox1.Image = Properties.Resources.noimage;
listBox1.Items.Clear();
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void label8_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void AddButton_Click(object sender, EventArgs e)
{
int u = 4;
int p = 4;
int c = 4;
int pop = 4;
int pro = 4;
int t = 4;
int r = 4;
univ[u+1].uni = textBox1.Text;
univ[p + 1].prov = textBox2.Text ;
univ[c + 1].city = textBox3.Text ;
univ[pop + 1].population = textBox4.Text ;
univ[pro + 1].programs = textBox5.Text;
univ[t + 1].tuition = textBox6.Text;
univ[r + 1].residence = textBox7.Text ;
StreamWriter sw = new StreamWriter("Universities.txt", true);
String line;
line = Console.ReadLine();
sw.WriteLine(univ[u + 1].uni + ", " + univ[p + 1].prov + ", " + univ[c + 1].city + ", " + univ[pop + 1].population + "," + univ[pro + 1].programs
+ ", " + univ[t + 1].tuition + "," + univ[r + 1].residence + ",");
MessageBox.Show("A University has been added.");
sw.Close();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("There are " + comboBox1.Items.Count + " universities.");
}
}
}
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//your code goes here
string[] sPlit = line.Split(',');
univ[i].uni = sPlit[0];
univ[i].prov = sPlit[1];
univ[i].city = sPlit[2];
univ[i].population = sPlit[3];
univ[i].programs = sPlit[4];
univ[i].tuition = sPlit[5];
univ[i].residence = sPlit[6];
comboBox1.Items.Add(univ[i].uni);
}
}
}
catch (Exception p) //catches errors
{
Console.WriteLine("Exception: " + p.Message);
}
finally //final statement before closing
{
Console.WriteLine("Executing finally block.");
}
Hope Helps
I need some guidance here on why this isn't working:
So here's the issue, I want to give my users a little status field so they can check how long it will take and get a coffee or two for them.
My Problem is that the statusfield (2 Labels), are not updated during the process.
This is my current code :
private void Cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void start_change_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Start process?", "DateChanger", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
if (dr == DialogResult.OK)
{
//get files
List<String> d = new List<String>();
label_status_title.Text = "Status: collecting Data, take a coffee while waiting.\nfiles changed: 0 files";
d = getFiles("H:\\");
int i = 0;
double diff = 0.0;
//modify files
label_status_title.Text = "Status: changing files.\nfiles changed: 0/" + d.Count + " files.";
foreach (String s in d)
{
String label = "\nfile: " + s;
//create newDate and modify creation and lastwrite
DateTime actualDate = Directory.GetLastWriteTime(s).Date;
DateTime newDate = new DateTime(2015, 03, 01);
diff = (newDate - actualDate).TotalDays;
label += "\nactual creation date: " + Directory.GetCreationTime(s).Date;
label += "\nnew creation date: " + newDate.Date;
label += "\nactual last write date: " + Directory.GetLastWriteTime(s).Date;
label += "\nnew last write date: " + newDate.Date;
if (diff > 400)
{
try
{
//set new timevalues
Directory.SetCreationTime(s, newDate);
Directory.SetCreationTimeUtc(s, newDate);
Directory.SetLastWriteTime(s, newDate);
Directory.SetLastWriteTimeUtc(s, newDate);
}
catch (UnauthorizedAccessException UAE)
{
}
i++;
label += "\nchange needed.";
}
else
{
label += "\nchange not needed.";
}
label_status.Text = label;
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
}
MessageBox.Show("Process finished, changed: " + i + "/" + d.Count + " files.");
}
}
private List<String> getFiles(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(getFiles(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
private void DateChanger_Load(object sender, EventArgs e)
{
String label = "";
label_status_title.Text = "Status: \nfiles changed: 0 files";
label += "file: ";
label += "\nactual creation date: ";
label += "\nnew creation date: ";
label += "\nactual last write date: ";
label += "\nnew crealast writetion date: ";
label_status.Text = label;
}
I also tried the suggestion of using MethodInvoker, but that also didn't work either. Any guidance or suggestions here are appreciated.
Thanks.
Mirko
p.s. if there is a better solution than using labels or text boxes for this feel free to tell me. :)
Youre Method start_change_Click(object sender, EventArgs e) is blocking the main thread. To avoid this, use a separate thread to update the labels.
Check out this post: Thread freezes main UI
Just refresh the Label after assigning it a new Text value.
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
label_status_title.Refresh(); //added
In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}