Write to text files - c#

Totally new to this. Depending on which event button I click I need to write to the appropriate text file. However, the input data writes to the same text file. How do I specify the appropriate text file it writes to and is saved.
The coding, identical apart from the name of the text file, I'm currently using is:
private void btnItemAdd_Click(object sender, EventArgs e)
{
string sItem;
string sNumber;
if (rdoDrinks.Checked == false && rdoConfectionary.Checked == false)
{
//Message to remind user to select category
MessageBox.Show("Please select a category");
txtItem.Focus();
}
{
{
if ((rdoDrinks.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
//Message to remind user to enter a number
MessageBox.Show("Please input a number");
txtItemNumber.Focus();
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))
{
//add Item to end of list
lstItems.Items.Add(string.Format("{0, -15} {1, -20}", txtItem.Text, txtItemNumber.Text));
txtCount.Text = lstItems.Items.Count.ToString();
//set focus to the text box
txtItem.Focus();
StreamWriter sw = File.AppendText("Drinks.txt");
{
sItem = txtItem.Text;
sw.WriteLine(sItem);
sNumber = txtItemNumber.Text;
sw.WriteLine(sNumber);
}
MessageBox.Show("Details have been saved");
txtItem.Clear();
txtItemNumber.Clear();
sw.Close();
}
else if ((rdoConfectionary.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
//Message to remind user to enter a number
MessageBox.Show("Please input a number");
txtItemNumber.Focus();
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))
{
//add Item to end of list
lstItems.Items.Add(string.Format("{0, -15} {1, -20}", txtItem.Text, txtItemNumber.Text));
txtCount.Text = lstItems.Items.Count.ToString();
//set focus to the text box
txtItem.Focus();
StreamWriter sw = File.AppendText("Confectionary.txt");
{
sItem = txtItem.Text;
sw.WriteLine(sItem);
sNumber = txtItemNumber.Text;
sw.WriteLine(sNumber);
}
MessageBox.Show("Details have been saved");
txtItem.Clear();
txtItemNumber.Clear();
sw.Close();
}
}
}
}

You have several issues:
You are missing an else after the first if.
The code below can never end up being true.
The two if statement collide (the txtItemNumber.Text comparison is the problem). Hence you will never end up writing to Drinks.txt:
if ((rdoDrinks.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
...
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))

Related

textbox text is checked only once

I have 2 panels. If textboxes are empty, there is a message. My problem is, say I get to second panel then go back and delete texts then go to second panel again, it does not show message. Is there a way to check the texts every time?
private void bttn_Next_Click(object sender, EventArgs e)
{
if (txt_FirstName.Text == " " || txt_LastName.Text == " " ||
txt_Email.Text == " " || txt_Contact.Text == " " ||
txt_HouseNumber.Text == " " || txt_Street.Text == " " ||
txt_Barangay.Text == " " || txt_Municipality.Text == "")
{
MessageBox.Show("Please complete all required fields.", "Message");
}
else
{
panel1.Hide();
panel2.Hide();
panel3.Show();
}
}
The correct way to check for empty string is as follows
private void bttn_Next_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txt_FirstName.Text) || string.IsNullOrWhiteSpace(txt_LastName.Text) ||
string.IsNullOrWhiteSpace(txt_Email.Text) || string.IsNullOrWhiteSpace(txt_Contact.Text) ||
string.IsNullOrWhiteSpace(txt_HouseNumber.Text) || string.IsNullOrWhiteSpace(txt_Street.Text) ||
string.IsNullOrWhiteSpace(txt_Barangay.Text) || string.IsNullOrWhiteSpace(txt_Municipality.Text))
{
MessageBox.Show("Please complete all required fields.", "Message");
}
else
{
panel1.Hide();
panel2.Hide();
panel3.Show();
}
}

entity Validation Exception on savechanges() in winforms

i'm developing an app for a veterinary clinic in winforms.
i have this table named "petOwner" which gives a foreign key to the table "Pets". now when im trying to register a pet i get information of both the owner and the pet from the user,enter code here the owner is saved successfully (savechanges()!=0) but when it comes to pet it gives me the entity validation err on the following code where triple starred:
if (gpbx_ownerInfo.Enabled==true)
{
objOwner.name = txt_ownerName.Text;
objOwner.family = txt_ownerFamily.Text;
objOwner.mobile = txt_ownerMobile.Text;
objOwner.tel = txt_ownerTel.Text;
objOwner.address = rtxt_ownerAdrs.Text;
objOwner.comment = rtxt_ownerCmnt.Text;
if (txt_ownerName.Text != "" & txt_ownerFamily.Text != "" & txt_ownerMobile.Text != "" & rtxt_ownerAdrs.Text != "")
{
if (objDB.Tbl_ownerInfo.Where(x => x.name == txt_ownerName.Text & x.family == txt_ownerFamily.Text & x.mobile == txt_ownerMobile.Text).ToList().Count == 0)
{
objDB.Tbl_ownerInfo.Add(objOwner);
}
else
{
MessageBox.Show("This keeper already exist\nTry finding them using the 'Keeper already Registered' link.");
}
}
else
{
MessageBox.Show("Fill the starred items please");
txt_ownerName.BackColor = Color.MistyRose;
txt_ownerFamily.BackColor = Color.MistyRose;
txt_ownerMobile.BackColor = Color.MistyRose;
rtxt_ownerAdrs.BackColor = Color.MistyRose;
}
if (objDB.SaveChanges() != 0)
{
gpbx_ownerInfo.Enabled = false;
objPet.ownerID = objDB.Tbl_ownerInfo.Max(s => s.ID);
objPet.name = txt_petName.Text;
objPet.species = txt_petSpecies.Text;
objPet.breed = txt_petBreed.Text;
objPet.birthDate = dt_petBDate.Value.Date;
if (cbox_petGender.Text == "Male")
{
objPet.gender = true;
}
else if (cbox_petGender.Text == "Female")
{
objPet.gender = false;
}
else
objPet.dominatingClr = txt_petClr.Text;
objPet.distinguishingMarks = rtxt_petMarks.Text;
if (txt_petName.Text != "" & txt_petSpecies.Text != "" & cbox_petGender.Text != "" & txt_petClr.Text != "" & cbox_petGender.Items.Contains(cbox_petGender.Text))
{
if (objDB.Tbl_Pets.Where(p => p.name == txt_petName.Text & p.species == txt_petSpecies.Text & p.breed == txt_petBreed.Text & p.dominatingClr == txt_petClr.Text).ToList().Count == 0)
{
objDB.Tbl_Pets.Add(objPet);
***if (objDB.SaveChanges() != 0)***
{
gpbx_ownerInfo.Enabled = true;
textCleaner();
MessageBox.Show("Pet registered successfully");
}
}
else
{
gpbx_ownerInfo.Enabled = false;
MessageBox.Show("This pet already exists");
}
now i know a lot of people don't get this in winforms they usually face it in asp.net
and i've searched a lot but every body has given answers on asp
here is the exception:enter image description here

Filter data from datatable for one of columns in asp.net

I have a datatable which fetches some records. So there is one column name as UPDATED_STATUS. In that column either Pre Hoto or Post Hoto value will come.
So what I want is, Either any one of those values should be their in that column then only the it should move ahead otherwise it should prompt alert as
Either Pre Hoto or Post Hoto can be their
Below is sample image for reference
Below is the code for getting the datatable with the UPDATED_STATUS column
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
Your current check (if (dtStatus == null && dtStatus.Rows.Count < 0)) is wrong:
when dtStatus is null, you continue checking dtStatus.Rows, which throws a nullref exception (you just found out that it was null);
Rows.Count is never less than zero.
Try if (dtStatus == null || dtStatus.Rows.Count == 0) to check whether there is no status at all (it is null) or no status rows (count is zero). The || will prevent checking for dtStatus.Rows when it was found that dtStatus is null.
&& means that both sides must be true at the same time.
|| means that at least of the sides must be true (both true is also fine).
Both don't evaluate the second test when the first already decided the outcome (false && whatever is always false, true || whatever is always true)
Are you looking for like this !
foreach (DataRow row in dtStatus.Rows)
{
if (string.IsNullOrEmpty(Convert.ToString(row["UPDATED_STATUS"])) ||
(Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "pre hoto" &&
Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "post hoto"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
break;
}
else { }
}
I have got a way to get this done.. Here I go
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
}
DataTable dtGetHotoPre = null;
var rows = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "PRE HOTO");
if (rows.Any())
{
dtGetHotoPre = rows.CopyToDataTable();
}
DataTable dtGetHotoPost = null;
var rowsPost = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "POST HOTO");
if (rowsPost.Any())
{
dtGetHotoPost = rowsPost.CopyToDataTable();
}
string strFlagStatus = "";
if (dtGetHotoPre != null)
{
if (dtGetHotoPost != null)
{
strFlagStatus = "No Process";
}
else
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPost;
}
}
else
{
if (dtGetHotoPost != null)
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPre;
}
else
{
strFlagStatus = "No Process";
}
}
// if(dtGetHotoPre != null && dtGetHotoPost != null)
if (strFlagStatus == "No Process")
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('The sites contains both Pre and Post Hoto Status, so it cannot be uploaded');", true);
}
else
{
// will move ahead.
grdDvHoto.DataBind();
}

error checking using bool and radiobuttons

I'd like to implement some error checking on my program.
If properties have not been selected my program should throw up an error message instructing the user to input the missing information.
I've implemented this for some properties but the final part which deals with radio buttons and bools is causing me trouble.
private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Adds Patients using buttone etc to set properties
{
string name = txtPatientName.Text,bloodType;
int x=1;
DateTime dob;
bool bloodA = rbA.IsChecked.Equals(true);
bool bloodB = rbB.IsChecked.Equals(true);
bool bloodAB = rbAB.IsChecked.Equals(true);
bool blood0 = rb0.IsChecked.Equals(true);
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false))
{
if (txtPatientName.Text == "")
{
MessageBox.Show("Please enter Patient's Name");
}
else if (dpDOB.SelectedDate == null)
{
MessageBox.Show("Please select a date");
}
else if (rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false))
{
MessageBox.Show("Please enter patient's blood type");
}
}
else
{
if (bloodA)
{
bloodType = "A";
}
else if (bloodB)
{
bloodType = "B";
}
else if (bloodAB)
{
bloodType = "AB";
}
else
{
bloodType = "0";
}
dob = dpDOB.SelectedDate.Value;
Patient patient = new Patient(name, bloodType, x, dob);
MainWindow mainWindow = Owner as MainWindow;
patients.Add(patient);
lstPatients.ItemsSource = null;
lstPatients.ItemsSource = patients;
// this.Close();
}
}
You already got the values captured in the blood# variables, so you may use one of these approaches:
Using the variables for your if statement:
if (!(bloodA || bloodB || bloodAB || blood0))
MessageBox.Show("Please enter patient's blood type");
Using a list (just one more line):
List<bool> rbValues = new List<bool>() { bloodA, bloodB, bloodAB, blood0 };
if (!rbValues.Any(b => b))
MessageBox.Show("Please enter patient's blood type");
Or making it reusable within your method, as you use it for other evaluations:
var anyBlood = (bloodA || bloodB || bloodAB || blood0)
...
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !anyBlood)
...
if (!anyBlood)
MessageBox.Show("Please enter patient's blood type");
Hope it helps

How to check two conditions in an IF statement in windows phone 7 application using c#?

I am building an application for windows phone 7 where i have a form and i need to validate two conditions here. The condition is that the textbox shouldnot contain null value and also the value should not be equal to *Name.
if(name.Text == String.Empty)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
Please help me to put the 2nd condition here
if ((name.Text == String.Empty) || (name.Text == "Name"))
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
You want to use the && operator, something like this
if (name.Text == String.Empty && name.Text != *Name)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
you need OR condition like below
if (string.IsNullOrEmpty(name.Text) || name.Text == "Name")
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
try this:
if (name.Text == null && name.Text != "Name")
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
if ((name.Text == String.Empty) || (name.Text == "Name"))
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
if (name.Text == String.Empty)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
else
{
if(name.Text == "Name"){
MessageBox.Show("Your error message");
name.Focus();
return false;
}
}

Categories