C# two message boxes popping up - need to stop one - c#

Both message boxes run after each other when no buttons are checked when only the following should show:
{ MessageBox.Show("Incomplete order. Please review.", "Incomplete Order."); }
How do I prevent the following messagebox from running when no buttons are checked?
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
"Code"
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}

You will go a long way if you changed
if (SmallPizza.Checked)
to
else if (SmallPizza.Checked)

You can exit the function after the first error message appears. just place a return; after the messagebox

Slight variation to the else if suggestions by Frank Pytel. Rather than changing subsequent if's to else if's it needs to be an if else for the first validation check then the series of if statements within the else block as follows..
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
else {
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}
}

You also can do like
if (MessageBox.Show("First MessageBox", "Test", MessageBoxButtons.OK) == System.Windows.Forms.DialogResult.OK) {
MessageBox.Show("Second messageBox", "Test", MessageBoxButtons.OK);
}

Okay entering return; did the trick. I tried putting the 'else if' in but both message boxes were still popping up.
Thanks guys. Most appreciated.

Related

how to efficiently simplify repetitive code {Objects/Strings}

First, I apologize for the length of this, but it's all I knew when I started. Now I'm experimenting with the foreach, List<t> and TreeView classes to avoid repetition as recmomended by SO community.
The form will collect information via text boxes, allow attachments of files with file dialogs and collate all info into a neat HTML bodied email. We sell slabs.. and my original code looked a little like this:
private void PrepareReturnEmailTwoSlabs()
{
LoadSettings();
string Fname = Properties.Settings.Default.FabricatorName;
string Facc = Properties.Settings.Default.FabricatorAccountNo;
string Fadd1 = Properties.Settings.Default.FabricatorAddress1;
string Fadd2 = Properties.Settings.Default.FabricatorAddress2;
string Ftown = Properties.Settings.Default.FabricatorTown;
string Fcounty = Properties.Settings.Default.FabricatorCounty;
string Fpostcode = Properties.Settings.Default.FabricatorPostcode;
string Fphoneno = Properties.Settings.Default.FabricatorPhone;
string Femail = Properties.Settings.Default.FabricatorEmail;
string Fclient = Properties.Settings.Default.ClientManagerEmail;
string Fcentre = Properties.Settings.Default.CentreEmail;
string FQt = Properties.Settings.Default.QTEmail;
string Dateofinv = dateTimePicker1.Value.ToShortDateString();
string Inv = textBox13.Text;
string Material1 = textBox14.Text;
string Thick1 = comboBox8.SelectedValue.ToString();
string Batch1 = textBox44.Text;
string Reason1 = comboBox1.SelectedValue.ToString();
string Notes = textBox18.Text;
string Thick2 = comboBox7.SelectedValue.ToString();
string Material2 = textBox15.Text;
string Batch2 = textBox45.Text;
string Reason2 = comboBox2.SelectedValue.ToString();
if (Thick2 == null)
{
Thick2 = "not selected";
}
if (Material2 == null)
{
Material2 = "not selected ";
}
if (Batch2 == null)
{
Batch2 = "not selected ";
}
if (Reason2 == null)
{
Reason2 = "not selected ";
}
GenerateUniqueRefReturn();
//construct email
var message = new MimeMessage();
message.From.Add(new MailboxAddress("************", "***************"));
message.To.Add(new MailboxAddress("**********", "********"));
message.Subject = "Return" + " " + Returnid;
//different message bodies dependant on how many slabs are chosen
TextPart body2 = new TextPart("html")
{
Text = #"Please See Below Information" + "<br/>" +
"<h4>Return ID: " + " " + Returnid + "</h4>" + "<br/>" +
"<b>Fabricator Name:</b>" + " " + Fname + "<br/>" + Environment.NewLine +
"<b>Account Number:</b>" + " " + Facc + "<br/>" + Environment.NewLine +
"<b>Address Line 1:</b>" + " " + Fadd1 + "<br/>" + Environment.NewLine +
"<b>Address Line 2:</b>" + " " + Fadd2 + "<br/>" + Environment.NewLine +
"<b>Town:</b>" + " " + Ftown + "<br/> " + Environment.NewLine +
"<b>County:</b>" + " " + Fcounty + "<br/>" + Environment.NewLine +
"<b>Postcode:</b>" + " " + Fpostcode + "<br/>" + Environment.NewLine +
"<b>Phone:</b>" + " " + Fphoneno + "<br/>" + Environment.NewLine +
"<b>Email:</b>" + " " + Femail + "<br/>" + Environment.NewLine + "<br/>" +
"<br/>" +
"<b>Date Of Invoice: </b>" + " " + DoI + "<br/>" +
"<b>Invoice: </b>" + " " + Inv + "<br/>" +
"<b>Material Information:</b>" + "<br/>" +
//slab 1
"<b>Thickness: </b>" + " " + Thick1 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material1 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch1 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason1 + "<br/>" + "<br/>" +
//slab 2
"<b>Thickness: </b>" + " " + Thick2 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material2 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch2 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason2 + "<br/>" + "<br/>" +
"<br/>" +
"<b>Notes:" + " " + Notes
};
var builder = new BodyBuilder();
//check for return attachment and if found, assign attachment to message via bodybuilder
if (checkBox5.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
message.Body = builder.ToMessageBody();
}
if (checkBox7.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
message.Body = builder.ToMessageBody();
}
if (checkBox6.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
builder.Attachments.Add(ReturnAttachment3);
message.Body = builder.ToMessageBody();
}
else
{
message.Body = body2;
}
//Connection to SMTP and Criteria to Send
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.gmail.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate("***************#********.com", "*********");
client.Send(message);
client.Disconnect(true);
This code was repeated all the way up to five slabs. So now, I have a class:
{
public string Thickness { get; set; }
public string Material { get; set; }
public string Batch { get; set; }
public Slab(string Thick, string Mat, string Batchno)
{
Thickness = Thick;
Material = Mat;
Batch = Batchno;
}
}
A List that holds this object:
private void button1_Click(object sender, EventArgs e)
{
string t = comboBox1.SelectedValue.ToString();
string m = comboBox2.SelectedValue.ToString();
string b = textBox6.Text;
Slab S = new Slab(t, m, b);
allSlabs.Add(S);
PaintTree();
}
public void PaintTree()
{
int ParentIndex;
TreeSlabs.Nodes.Clear();
foreach (Slab slab in allSlabs)
{
TreeSlabs.BeginUpdate();
TreeSlabs.Nodes.Add("Slab" + " " + (allSlabs.IndexOf(slab) + 1).ToString());
ParentIndex = allSlabs.IndexOf(slab);
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Thickness: " + $"{slab.Thickness}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Material: " + $"{slab.Material}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Batch: " + $"{slab.Batch}");
TreeSlabs.EndUpdate();
}
}
Now i want to create a foreach.. that iterates through each node.. and collects the info from the parent and its children foreach node, and somehow instantiate new HTML methods for each node..
Foreach Node:
Compose HTML Line - new HTML
Slab 1:
Thickness:
Material
Batch
Slab 2:... etc
If theres 8 nodes, it generates 8 of those bodies. i can think of ways.. but i KNOW they're defintely not the correct ways to go about it based on what ive read and seen out there.
Many Thanks
You don't need to iterate through the tree and try to reclaim the data you put into it from the List of Slabs; it would be simpler to enumerate the List:
By the way, some other tips:
don't beginupdate/endupdate inside the loop, do it outside
the Add method that adds a node to a tree returns the node it added; you don't have to find it again by index, just capture it var justAdded = rootnode.Add("parent node"); and then add your thickness etc to it justAdded.Nodes.Add("thickness..."). The only add command that doesn't return the added mode is the one that takes a treenode type object; it doesn't need to return it because you already have it
consider adding a method to your slab to return some html, to simplify things
you can tidy all that html up with some string interpolation like you did with your $"{slab.thickness}" etc

Is there any to shorten the code that needs variables?

I've always wondered, are there ways to shorten this kind of code?
private void Update01()
{
item01.text = item01n + "\nCost: " + Math.Round(cost01, 2) + "\nYou have: " + n01;
}
private void Update02()
{
item02.text = item02n + "\nCost: " + Math.Round(cost02, 2) + "\nYou have: " + n02;
}
private void Update03()
{
item03.text = item03n + "\nCost: " + Math.Round(cost03, 2) + "\nYou have: " + n03;
}
.
.
.
Thanks for the help.
As 12seconds said, just return a string and pass in 3 variables:
private string GetUpdate(item, cost, n)
{
return item + "\nCost: " + Math.Round(cost, 2) + "\nYou have: " + n;
}
And then simply do:
item01.text = GetUpdate(item01n, cost01, n01);
item02.text = GetUpdate(item02n, cost02, n02);
item03.text = GetUpdate(item03n, cost03, n03);

Insert Word Heading with Selection

I try to insert a word heading at a specific position but it is always added at the end of the document. Where is my mistake?:
foreach (Publish p in tempstructure)
{
if (p.element_type_id == 3)
{
Word.Paragraph par = selection.Paragraphs.Add();
par.Range.Text = "test";
par.Range.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
par.Range.InsertParagraphAfter();
selection.TypeParagraph();
}
else
{
if (File.Exists(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx"))
{
selection.InsertFile(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx");
selection = word.Selection;
}
else
{
selection.TypeText("Missing file: " + p.filename + "_" + language + ".docx");
selection.TypeParagraph();
}
}
selection = word.Selection;
}
Best regards ...
The simple solution is:
foreach (Publish p in tempstructure)
{
if (p.element_type_id == 3)
{
selection.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
selection.TypeText(p.name);
selection.TypeParagraph();
}
else
{
if (File.Exists(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx"))
{
selection.InsertFile(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx");
selection = word.Selection;
}
else
{
selection.TypeText("Missing file: " + p.filename + "_" + language + ".docx");
selection.TypeParagraph();
}
}
selection = word.Selection;
}

Input string was not in the correct format with Entity Framework

I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.

How to print content of selected item in ListView into a textbox when selected?

I'm trying to display content of the selected row into text box. This code doesn't work because it only add first selected item.
EDIT: This kind of work but my display look like this: ListViewSubItem: {a} ListViewSubItem: {b}
if (!string.IsNullOrEmpty(PC.SubItems[1].Text) && !string.IsNullOrEmpty(PC.SubItems[2].Text))
{
txtPc.Text = e.Item.SubItems[1].ToString()
+ " " + e.Item.SubItems[2].ToString();
}
EDIT: This works well:
private void SelectedItem(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (tabSelectPage.SelectedTab != tabPage2)
txtSelected.Text = "User: " + e.Item.SubItems[1].Text +
"Pass" + e.Item.SubItems[2].Text;
else
txtSelected.Text = "URL: " + e.Item.SubItems[1].Text +
"User: " + e.Item.SubItems[2].Text +
"Pass" + e.Item.SubItems[3].Text;
}
This is how I have done it:
private void SelectedItem(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (tabSelectPage.SelectedTab == tabPage1)
txtSelected.Text = " User Name: " + e.Item.SubItems[1].Text +
" Password: " + e.Item.SubItems[2].Text;
else if (tabSelectPage.SelectedTab == tabPage2)
txtSelected.Text = " URL: " + e.Item.SubItems[1].Text +
" User Name: " + e.Item.SubItems[2].Text +
" Password: " + e.Item.SubItems[3].Text;
else if (tabSelectPage.SelectedTab == tabPage3)
txtSelected.Text = " Software Name: " + e.Item.SubItems[1].Text +
" Serial Code: " + e.Item.SubItems[2].Text;
}
Use the ListViewItemSelectionChangedEventArgs.ItemIndex property.

Categories

Resources