If statement for fileOut not working properly - c#

I am fairly new to C# programming and am having some trouble figuring out how to perform this. I am trying to say in the program that if the textBoxes are not filled in than streamWriter should not send anything to the file and a messageBox pops up. As of now only the messageBox pops up but information is still being sent to the file. I am trying to use something like this if ((fileOut != null)) however I am not finding a good place to insert it or if this is what should be used. Any help would be much appreciated. Thanks!
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Calculate payroll
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
decimal hoursWorked;
decimal hourlyPayRate;
decimal basePay;
decimal overtimeHours;
decimal overtimePay;
decimal grossPay;
// Get the hours worked and hourly pay rate.
hoursWorked = decimal.Parse(txtHoursWorked.Text);
hourlyPayRate = decimal.Parse(txtHourlyRate.Text);
// Determine the gross pay.
if (hoursWorked >= 40)
{
// Calculate the base pay (without overtime).
basePay = hourlyPayRate * 40;
// Calculate the number of overtime hours.
overtimeHours = hoursWorked - 40;
// Calculate the overtime pay.
overtimePay = overtimeHours * hourlyPayRate * 1.5m;
// Calculate the gross pay.
grossPay = basePay + overtimePay;
}
else
{
// Calculate the gross pay.
grossPay = hoursWorked * hourlyPayRate;
}
// Display the gross pay.
lblGrossPay.Text = Convert.ToString(grossPay);
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
} //Writes text to files
StreamWriter fileOut = new StreamWriter("employeePay.dat", true);
//if (!(fileOut != null))//I am trying this. However stated this way nothing is passed to the file
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
fileOut.Close();
LoadContacts();
}
// Clear all text from output labels & input textboxes
private void btnClera_Click(object sender, EventArgs e)
{
// Clear the TextBoxes and gross pay label.
txtName.Text = "";
txtNumber.Text = "";
txtHoursWorked.Text = "";
txtHourlyRate.Text = "";
lblGrossPay.Text = "";
// Reset the focus.
//txtHoursWorked.Focus();
}
// End program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
void LoadContacts()
{
try
{
lstEmployeePay.Items.Clear();
string employeePay;
if (File.Exists("employeePay.dat"))
{
StreamReader fileIn = new StreamReader("employeePay.dat");
while (!fileIn.EndOfStream)
{
employeePay = fileIn.ReadLine();
string[] fields = employeePay.Split(',');
lstEmployeePay.Items.Add(fields[0]);
lstEmployeePay.Items.Add(fields[1]);
lstEmployeePay.Items.Add(fields[2]);
lstEmployeePay.Items.Add(fields[3]);
lstEmployeePay.Items.Add(fields[4]);
lstEmployeePay.Items.Add("");
}
fileIn.Close();
}
}
catch (FileNotFoundException ex)
{
MessageBox.Show("The file does not exist, please try again");
}
catch (Exception ex)
{
}
}
}
}

All you need is a return statement after showing the message box. Like
MessageBox.Show("");
return;
I would also like to make some other recommendations here.
You can check if the textboxes are empty by doing
if(string.IsNullorWhiteSpace(yourtextboxt.text)
You should do the parsing using decimal.tryparse. It will not throw an exception.

You need to move your stream writer within the exception handling as everything after the catch still gets executed.
I would also consider wrapping the StreamWriter in a using statement to guarantee it is closed when the function exits.
try
{
// other code here
using(var fileOut = new StreamWriter("employeePay.dat", true)
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
}
catch(...)
{
MessageBox();
}
// any code after the catch will still execute

Related

foreach loop syntax error C# Visual Studio 2013 ultimate

Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current 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 DriversLicenseExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] answerArray ={"B","D","A","A","C",
"A", "B","A","C","D",
"B", "C","D","A","D",
"C", "C","B","D","A"};
string[] studentansArray = new string[20];
List<string> incorrectList = new List<string>();
int count = 0, index = 0, qnumber = 0;
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
}
foreach (string str in incorrectList) // <<-- error is here
{
lbox.Items.Add(str);
} // <<-- error is here
catch (Exception)
{
MessageBox.Show("File Not Found");
}
}
private void button2_Click(object sender, EventArgs e)
{
filenametxt.Text = "";
resultoutput.Text = "";
lbox.Items.Clear();
}
private void exitbutton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
foreach (string str in incorrectList)
{
lbox.Items.Add(str);
}
}
catch (Exception)
{
MessageBox.Show("File Not Found");
}

Accessing RowCount from another class

I have a winform, that takes a number of params, executes an stored procedure and then populates a DataGridView with the results.
What I'd like to do is add a string the bottom of my winform that returns a message, including a count of total rows returned.
This presently works fine, using the following syntax :
deskSearchResultCount.Text = String.Format("Your search returned {0} results", deskDataGridView.RowCount );
However as the majority of my application has been written out in the initial form, I was moving sections into classes, to 'tidy it up' a bit - (I'm still very new to c# so apologies if this is a n00b mistake)
Once I add a class called Summary, I would like to call my RowCount as follows :
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
With my Summary class containing the following :
public class Summary : ContactAnalysisToolbox
{
public int Total(string type)
{
if (type == "Desk")
{
return deskDataGridView.Rows.Count;
}
else
{
return visionDataGridView.Rows.Count;
}
}
However the returned count is always 0. When stepping through the process also, at no point does it appear to be attempting to set itself as anything different.
Can anyone please help / point me in the right direction?
Thanks.
Edit -
I've included the full form also -
using System;
using System.Diagnostics;
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.DirectoryServices.AccountManagement;
using System.IO;
//
// Todo :
// -- Capture Assigned Team In Output
//
//
namespace CallsAnalysisToolbox
{
public partial class ContactAnalysisToolbox : Form
{
public ContactAnalysisToolbox()
{
InitializeComponent();
// Grabs username for current user and displays a welcome message
this.welcomeMessage.Text = "Welcome " + UserPrincipal.Current.Name;
}
private void searchVision_Click(object sender, EventArgs e)
{
try
{
// Run sp_incomingCalls on SQLCLUSTER
this.rep_IncomingCallsTableAdapter.Fill(this.visionReportsDataSet.Rep_IncomingCalls, dateTimePicker1.Value, dateTimePicker2.Value, textBox1.Text, textBox2.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
// Make export button active when search returns results
exportVisionButton.Enabled = (visionDataGridView.Rows.Count > 0);
// Assign returned row count to visionSearchResultCount label and then display label
visionSearchResultCount.Text = String.Format("Your search returned {0} results", visionDataGridView.RowCount);
visionSearchResultCount.Visible = true;
}
private void searchDesk_Click(object sender, EventArgs e)
{
try
{
// Run sp_caseActivity on SQLCLUSTER
this.rPT_CaseActivityTableAdapter.Fill(this.deskDataSet.RPT_CaseActivity, deskFrom.Value, deskTo.Value, deskClientList.Text, deskBenefitList.Text, deskStatusList.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (deskDataGridView.Rows.Count > 0)
{
exportDeskButton.Enabled = true;
deskSearchResultCount.Visible = true;
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
deskSummaryData.Visible = true;
noDataDesk.Visible = false;
// Populate the summary tab
// Get Email / Phone case count
deskTotalCaseResults.Text = deskDataGridView.RowCount.ToString();
//deskTotalEmailCasesResults.Text = emailCount.ToString();
//deskTotalPhoneCasesResults.Text = phoneCount.ToString();
}
}
//TODO : Combine Export functions. Ideally just a single function rather than the repeated logic within the Export class for each datagrid
private void exportVisionButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Vision");
}
private void exportDeskButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Desk");
}
private void deskDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// Limit 'open case in browser' action to first cell
if (deskDataGridView.CurrentCell.ColumnIndex.Equals(0))
{
string url = string.Format("https://qa.internal.local/agent/case/{0}", deskDataGridView.Rows[e.RowIndex].Cells[0].Value);
Process.Start(url);
}
}
}
}
For example you could do something like this. It's called Method Extension
Try this
public static class Helpers
{
public static string ToTotalCount(this DataGridView item)
{
return string.Format("Your search returned {0} results", item.Rows.Count);
}
}
In your form make sure that the namespace of the class Helpers is in the usings:
deskSearchResultCount.Text = deskDataGridView.ToTotalCount();

Writing Out a Textbox Produces Unexpected Results

I have created 2 text boxes that take the name and email address, stores it in a "text" file and display the contents in a list box. I have everything done but when it displays in the list box this is the output that I get.
"System.Windows.Forms.TextBox, Text: tony"
"System.Windows.Forms.TextBox, Text: tony#tony.com"
Can anyone tell me why it is doing that please? I'm still new to c# and I know this is a minor thing I just do not know where to look
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 _iLab_Week7
{
public partial class Form1 : Form
{
private StreamReader inFile; //streamreader for input
private StreamWriter outFile; //streamwriter for output
const string filename = "contacts.txt";
public Form1()
{
InitializeComponent();
}
private void btnAddContact_Click(object sender, EventArgs e)
{
//Disable the "add contact" and "email"
btnAddContact.Enabled=false;
txtBoxEmail.Enabled=false;
//check for and create contacts.txt file
if(!File.Exists(filename))
File.Create(filename);
if(File.Exists(filename))
{
try
{
//create the file stream
outFile = new StreamWriter(filename, true);
//get the item from the name and email text box
//write it to the file
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
//close the file
outFile.Close();
//clear the textbox
txtBoxName.Text="";
txtBoxEmail.Text="";
//the cursor in the text box
txtBoxName.Focus();
txtBoxEmail.Focus();
}
catch (DirectoryNotFoundException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
catch (System.IO.IOException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
string listItem;
this.lstBoxContact.Items.Clear();
btnAddContact.Enabled = false;
try
{
//open file for reading
inFile=new StreamReader(filename);
//read from file and add to list box
while ((listItem=inFile.ReadLine()) !=null)
{
this.lstBoxContact.Items.Add(listItem);
}
//Close the file
inFile.Close();
}
catch (System.IO.IOException exc)
{
this.lstBoxContact.Items.Add(exc);
}
}
else
{
this.lstBoxContact.Items.Add("File Unabailable");
}
}
private void lstBoxContact_SelectedIndexChanged(object sender, EventArgs e)
{
//enable button
btnAddContact.Enabled = true;
txtBoxName.Enabled = true;
txtBoxEmail.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
//make sure files are closed
try
{
inFile.Close();
outFile.Close();
}
catch { }
}
}
Replace
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
with
outFile.WriteLine(txtBoxName.Text);
outFile.WriteLine(txtBoxEmail.Text + "\n");
and try...
ADDED : When you say txtBoxName, you are referring to the txtBoxName object as a whole, which contains many properties - like Text, ForeColor, Font etc.... To get only the value or content, you need to specify the property which gives you that - which is the Text property
More about TextBox
outFile.WriteLine(txtBoxName);
is equivalent to
outFile.WriteLine(txtBoxName.ToString());
For most classes, the ToString() method is the same as Object.ToString(). This method just displays the name of the type of the instance you're trying to display. So you might have only seen
System.Windows.Forms.TextBox
However, the TextBox class helpfully overrides this method and displays both the type name and the value of the Text property.
But as Saagar Elias Jacky said. This is not what you actually intended to do, so just display txtBoxName.Text as he suggested.

I'm trying to change the color of each of a set of buttons using C#/Visual studio but nothing happens

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;
namespace Cameron_PickerillTrinitapoli_Assn1
{
public partial class seasonalBttnChanger : Form
{
public seasonalBttnChanger()
{
InitializeComponent();
}
//Triggers when program first loads
//Sets up
private void bttnChanger_Load(object sender, EventArgs e)
{
List<Button> lstTxt = new List<Button>
{
bttnSpring, bttnSummer, bttnAutumn, bttnWinter
};
//Wiring up event handlers in run time
foreach (Button txt in lstTxt)
{
txt.MouseEnter += button_MouseEnter;
txt.MouseLeave += button_MouseLeave;
}
}
// Sets up different background colors for TextBoxes
//* Static values for the color of each button need
//to be added.
//**Not what I was trying to accomplish
//**This needs to go somewhere else
void button_MouseEnter(object sender, EventArgs e)
{
try
{
// Event handlers always pass the parameter "sender" in as an object.
// You have to downcast it back to the actual type.
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
// stkColor.Push(txt.BackColor);
//txt.BackColor = Color.Red;
bttnName = txt.Name;
if (bttnName == bttnNameSpring)
{
txt.BackColor = Color.LightGreen;
}
else if (bttnName == bttnNameSummer)
{
//txt.BackColor = Color.Red;
txt.BackColor = Color.Red;
}
else if (bttnName == bttnNameAutumn)
{
txt.BackColor = Color.Yellow;
}
else if (bttnName == bttnNameWinter)
{
txt.BackColor = Color.Cyan;
}
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
//Handler for mouse leaving the button
void button_MouseLeave(object sender, EventArgs e)
{
try
{
Button txt = (Button)sender;
//txt.BackColor = stkColor.Pop();
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
}
}
}
Alright, so I'm just trying to create a simple program that changes the background colors of these buttons to some plain colors when you mouse over them. I had the same thing working using TextBox, but I need to get it working with button. I changed everything over to use the Button class, and it seems to have all the same functionality, but now the program runs, but nothing happens when you mouse over the buttons.
I'm pretty new to c#, stack exchange, and only slightly less so to programming in general, so sorry if I'm dinking up on etiquette/formatting my questions, etc.
I think you are trying to reference your buttons title when you are actually calling the button name
Changing:
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
To:
String bttnName = null;
String bttnNameSpring = "bttnSpring";
String bttnNameSummer = "bttnSummer";
String bttnNameAutumn = "bttnAutumn";
String bttnNameWinter = "bttnWinter";
Causes the code to work.
If you do infact want to use the "Spring", "Summer" etc reference than i would suggest changing
bttnName = txt.Name;
to
bttnName = txt.Text;
And ensure that the Text of the labels is set correctly

Databound DateTimePicker Time in C#

I'm have a Windows Form with 2 datetimepicker controls: one for date and a separate datetimepicker control for time. Both of these controls are bound to the same column in a database and the controls have different property names (i.e., dateEdit and timeEdit) and different formats (i.e., Long and Time).
Here are my problems/questions:
The timeEdit picker ignores whatever seconds are in the database entry and sets the time seconds to "00", as in "2:34:00", even though the database entry (trimmed to time for this illustration) is "14:34:31.891123 -04:00". How can I get the seconds to correctly display?
Whenever I edit the seconds in the timeEdit picker from "00" to (for example) "15", as in "2:34:15", the picker resets the seconds to "00" before passing the value to the next function. How do I pass the correct seconds value?
I'd like to edit the milliseconds on the time. Is it best for me to bind the trimmed milliseconds (using DATEPART) to a text box? Will I need to convert or cast the milliseconds to a char or string in order to correctly display them in a text box?
Thanks for any help!
Code to trigger the edit form:
private void timeDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 5)
{
EditTime editForm = new EditTime((Guid)timeDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
editForm.StartPosition = FormStartPosition.CenterScreen;
editForm.ShowDialog();
editForm.Close();
}
}
catch (Exception ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
}
Code for the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace StatusManager
{
public partial class EditTime : Form
{
private Guid calendarId;
public EditTime()
{
InitializeComponent();
}
public EditTime(Guid Id)
{
InitializeComponent();
calendarId = Id;
}
public string GetConnectionString()
{
var connString = ConfigurationManager.ConnectionStrings["StatusManager.Properties.Settings.StatusConnectionString"].ConnectionString;
return connString;
}
private void UpdateCalendarItem(string dateEdit, string timeEdit, string note)
{
var conn = new SqlConnection(GetConnectionString());
const string UpdateStatusSql = #"UPDATE dbo.statuses SET
calendarTime = #timeOffset
notes = #note
WHERE PK_calendarUID = #PK_calendarUID";
try
{
SqlCommand cmd = new SqlCommand(UpdateSql, conn);
var param = new SqlParameter[3];
param[0] = new SqlParameter("#PK_calendarUID", calendarId);
//Convert date(s) to correct format
string dateTimeCombined = dateEdit + " " timeEdit;
DateTime timeConverted = Convert.ToDateTime(dateTimeCombined);
DateTimeOffset timeOffset = new DateTimeOffset(timeConverted);
param[1] = new SqlParameter("#timeOffset", timeOffset);
param[2] = new SqlParameter("#note", note);
foreach (SqlParameter t in param)
{
cmd.Parameters.Add(t);
}
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = "Error updating 'calendarItems': ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private void editTimeButton_Click(object sender, EventArgs e)
{
UpdateCalendarItem(dateEdit.Text, timeEdit.Text, notes.Text);
this.Close();
}
private void EditTime_Load(object sender, EventArgs e)
{
this.locationsTableAdapter.Fill(this.locationsDataSet.locations);
this.calendarTableAdapter.FillById(this.calendarDataSet.calendarItems, calendarId);
}
}
}
Code for instantiating the datetimepicker:
this.timeEdit.CustomFormat = "";
this.timeEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.calendarBindingSource, "calendarTime", true));
this.timeEdit.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.timeEdit.Location = new System.Drawing.Point(385, 30);
this.timeEdit.Name = "timeEdit";
this.timeEdit.ShowUpDown = true;
this.timeEdit.Size = new System.Drawing.Size(89, 20);
this.timeEdit.TabIndex = 2;
You need to use DateTimePicker.CustomFormat Property
s The one- or two-digit seconds.
ss The two-digit seconds. Single digit values are preceded by a 0.
You can't use DateTimePicker for milliseconds.
Problem solved but I'm not exactly sure how. Here's what I did:
In calendarDataSet, I updated both queries (Fill,GetData and FillById,GetDataBy (#ID)) to select calendarTime as CONVERT(VARCHAR(12), calendarTime, 114) AS calHoursMinsSec
In essence, I created created a new column with the hours, minutes, seconds, and milliseconds
On the form, I added a textbox and bound the textbox to calHoursMinsSec
Note: My previous attempts to convert the datetime to a varchar to were unsuccessful no doubt due to operator error.
Once I saved the form, the binding seemed to stick and I was able to pass the relevant variables to the update function
Thanks for everyone's input! I appreciate the guidance and suggestions!

Categories