I have been given a coding assignment by my recruiter for a job as a junior developer. There were three choices and I went with a problem that requires calculating a purchase. All items are supposed be taxed 10% unless they are books, food or medicine. Anything imported is taxed an extra 5%, even if they are tax exempt. So I created a form that allows a user to type in the name of the item, two check boxes for whether they are imported or tax exempt, a textbox for inputing price, and a text box for each input. Underneath is a textbox that is supposed to calculate the total sales tax, underneath that is a textbox for the total. The first checkbox is named "Item1Import" the next one is called "Item1Exempt." The price text box is named "Item1Price" and the other "Item1Output." And for each item the number would change, Item2Import, Item3Import, etc. The last two textboxes are called "SalesTax" and "Total."
Here is the code I have so far.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Item1Price_TextChanged(object sender, EventArgs e)
{
if(Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.05).ToString("C2"));
}
else if(Item1Exempt.Checked && !Item1Import.Checked)
{
Item1Output.Text = (Convert.ToInt32(Item1Price.Text)).ToString("C2");
}
else if(!Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text) + (Convert.ToInt32(Item1Price.Text) * 0.1) + (Convert.ToInt32(Item1Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.1)).ToString("C2");
}
}
private void Item2Price_TextChanged(object sender, EventArgs e)
{
if (Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.05).ToString("C2"));
}
else if (Item2Exempt.Checked && !Item2Import.Checked)
{
Item2Output.Text = (Convert.ToInt32(Item2Price.Text)).ToString("C2");
}
else if (!Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text) + (Convert.ToInt32(Item2Price.Text) * 0.1) + (Convert.ToInt32(Item2Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.1)).ToString("C2");
}
}
private void Item3Price_TextChanged(object sender, EventArgs e)
{
if (Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.05).ToString("C2"));
}
else if (Item3Exempt.Checked && !Item3Import.Checked)
{
Item3Output.Text = (Convert.ToInt32(Item3Price.Text)).ToString("C2");
}
else if (!Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text) + (Convert.ToInt32(Item3Price.Text) * 0.1) + (Convert.ToInt32(Item3Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.1)).ToString("C2");
}
}
private void Item4Price_TextChanged(object sender, EventArgs e)
{
if (Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.05).ToString("C2"));
}
else if (Item4Exempt.Checked && !Item4Import.Checked)
{
Item4Output.Text = (Convert.ToInt32(Item4Price.Text)).ToString("C2");
}
else if (!Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text) + (Convert.ToInt32(Item4Price.Text) * 0.1) + (Convert.ToInt32(Item4Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.1)).ToString("C2");
}
}
private void SalesTax_TextChanged(object sender, EventArgs e)
{
SalesTax.Text = (((Convert.ToInt32(Item1Output.Text) - Convert.ToInt32(Item1Price.Text)) + ((Convert.ToInt32(Item2Output.Text) - Convert.ToInt32(Item2Price.Text)) + ((Convert.ToInt32(Item3Output.Text) - Convert.ToInt32(Item3Price.Text)) + ((Convert.ToInt32(Item4Output.Text) - Convert.ToInt32(Item4Price.Text)).ToString("C2"));
}
private void Total_TextChanged(object sender, EventArgs e)
{
Total.Text = ((Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)).ToString("C2"));
}
}
}
The first problem I'm having is whenever I do type into Item1Price, it outputs to Item1Output but it doesn't work with the others, and the "salestax" and "total" textboxes don't show anything either.
The second problem is I can't type a number like "O.OO" but I can do "00" and whenever I delete the number, it crashes.
Any help would be really appreciated. Thank you in advance.
First thing its not in good fashion to post coding assignment in a forum to get help with for a job. If you cant complete the coding assignment by yourself I would suggest you reevaluate your skills and ask yourself if your ready for the position that you're trying to obtain. With that said I remember the days in my beginning when I was going after those positions I probably had no business being in at the time so I can sympathize with that. Now to your code.
First of all, you need to surround your conversions in a try catch block, the reason your application is crashing is because 0.00 will not convert into a integer since there is a decimal there. 00 will work but when you delete them your textbox.text value is now nothing which is not going to convert either and your program will crash. So you will need to add logic to handle an empty string value and not do a conversion. I would suggest you use decimal datatype when dealing with money values. As suggested also I would create a method in which you could pass the check box values and return a string value back to set your textbox values. This could clean up your event handler code cause it seems your calculations are the same.
Related
This question already has answers here:
Increment a string value
(4 answers)
Closed 2 years ago.
i am trying to code a counter for a social project im working on. i am using a windows form. i used a textbox to get my starting digit and a start and stop button.
code wise i manege to make it send the messges and everything but im running into a problem on the counting part. i get the errore of cant convert int into a string or it will add a number onto the already existing number example of what it sends: 1, 11, 111, 1111. instead of 1, 2, 3, 4, and so on
this is the part were im messing up on
textBox1.Text = textBox1.Text + 1;
SendKeys.Send("{Enter}");
Thread.Sleep(1000);
and here is the whole 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.Threading;
namespace Counting_Bot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void timer1_Tick(object sender, EventArgs e)
{
SendKeys.Send(textBox1.Text);
textBox1.Text = textBox1.Text + 1;
SendKeys.Send("{Enter}");
Thread.Sleep(1000);
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
public void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
}
}
im sorry for the bad wording and formating but im new here ¬.¬
The content within your textbox is a string, not an int. The +-operator for strings is implemented in a way that just concatenates the string to the end of the first one. So "1" + "1" returns "11", as "Hello " + "World" returns "Hello World".
You have to convert your text to a number first:
if(int.TryParse(textBox1.Text, out var number)
{
textBox1.Text = (number + 1).ToString();
}
textBox1.Text is of type string, therefore + concatenates textBox1.Text and 1 (which is implicitly converted to string).
You need to parse textBox1.Text as an integer:
textBox1.Text = (int.Parse(textBox1.Text) + 1).ToString();
Now + performs a mathematical addition.
You probably also want to validate your input, to ensure a valid integer has been entered:
if (int.TryParse(textBox1.Text, out int i))
{
textBox1.Text = (i + 1).ToString();
}
While the operator is editing the text box, he should be able to make mistakes like typing letters, or even removing everything, as long as you are certain that the operator typed a number when he is finished and presses the button to notify you that he is finished.
Usually you let the operator know that the input is not correct by disabling this button. If the button is enabled, then you know in your button-clicked event handler that the Text in the button is the textual representation of a number.
Subscribe to event TextBox.TextChanged to enable and disable the button
Subscribe to event Button.Clicked to process the typed text
The following is usually done using the visual studio designer:
TextBox textBox1 = new TextBox();
Button button1 = new Button();
textBox1.TextChanged += OnTextBoxTextChanged;
button1.Clicked += OnButtonClicked;
In your form:
int parsedInput = 0;
private void OnTextBoxChanged(object sender, ...)
{
// get the input text
string input = textBox1.Text;
// try to parse the input text. If this can be done, remember the parsedInput
// enable the button if the input is parsed correctly
button1.Enabled = (Int32.TryParse(input, out parsedInput);
}
private void OnButtonClicked(object sender, ...)
{
// Because the button is enabled, you know that parsedInput contains the parsed text
this.ProcessInput(this.parsedInput);
}
private int GetInput()
{
Int32.TryParse(input, out int i);
I'm new to C# and I'm trying to do a simple task. I'm trying to make an if statement for my program where if the user enters a number less than 100, it multiplies by .1 and shows the answer in a message box. But everytime I run the program the message box gives me back 0 for an answer rather than 6.5 for 65 for example. I am probably just missing something easy in my code here, please take a look.
public partial class Form1 : Form
{
private double discountAmt;
public Form1()
{
InitializeComponent();
}
private void DiscountCalculation(object sender, EventArgs e)
{
double Price = 0;
double.Parse(PriceBox.Text);
if (Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show(" The discount is " + discountAmt.ToString());
}
}
}
}
Look at this line:
double.Parse(PriceBox.Text);
It parses the textbox, but doesn't do anything with the result. You want this:
double Price = double.Parse(PriceBox.Text);
Even better is to use double.TryParse(), and also when working with money use the decimal type rather than double.
private void DiscountCalculation(object sender, EventArgs e)
{
decimal Price = 0.0m;
if (decimal.TryParse(PriceBox.Text, out Price) && Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show($"The discount is {discountAmt}");
}
}
I usually figure things out but this has me beat.
I have an array of listboxes on a form and a submit button. The user can pick items from any listbox then click the submit button to choose the confirm the item, but what needs to happen is that if they select something from listbox 1 then change their mind and select something from listbox 2, the item selected in listbox 1 should become unselected.
I can code that in to the eventhandlers but the problem is as soon as I change a value in another listbox programatically it fires another event. I can't seem to logic my way out of it.
Any ideas would be great otherwise I guess I will just have to put multiple submit buttons.
EDIT:
I figured out what I think is quite an obvious and simple solution in the end. I made use of the focused property to distinguish whether the user or the program was making changes. Works for both mouse and keyboard selections.
Thanks for the suggestions...
for (int i = 0; i < treatments.Length; i = i + 1)
{
this.Controls.Add(ListBoxes[i]);
this.Controls.Add(Labels[i]);
this.Controls.Add(Spinners[i]);
Labels[i].Top = vPosition - 20;
Labels[i].Left = hPosition;
Labels[i].Width = 600;
ListBoxes[i].Left = hPosition;
ListBoxes[i].Top = vPosition;
ListBoxes[i].Width = 600;
Spinners[i].Top = vPosition + ListBoxes[i].Height;
Spinners[i].Left = hPosition + ListBoxes[i].Width - 60;
Spinners[i].Width = 40;
for (int d = 25; d > 0; d = d - 1) { Spinners[i].Items.Add((d).ToString()); }
Spinners[i].SelectedIndex = 24;
//EVENT HANDLER CODE that is executed if any selectetindexchange in any LIstbox in array
ListBoxes[i].SelectedIndexChanged += (sender, e) =>
{
for (int s = 0; s < i; s = s + 1)
{
//FIND WHICH LBs[s] IS THE SENDING LISTBOX
if (ListBoxes[s] == sender && ListBoxes[s].Focused == true)
{
string msg = "sender is ListBox " + s.ToString() + "\nFocus is" + ListBoxes[s].Focused.ToString();
// MessageBox.Show(msg);
}
else if(ListBoxes[s].Focused==false)
{
ListBoxes[s].SelectedIndex = -1;
}
}
}; //end of event handler
}
I generally solve this kind of problem with a flag that lets me know that I am changing things, so my event handlers can check the flag and not take action in that case.
private int codeChangingCount = 0;
private void combobox1_SelectedIndexChanged(object sender, EventArgs e) {
codeChangingCount++;
try {
combobox2.SelectedIndex = someNewValue;
} finally {
codeChangingCount--;
}
}
private void combobox2_SelectedIndexChanged(object sender, EventArgs e) {
if (codeChangingCount == 0) {
//I know this is changing because of the user did something, not my code above
}
}
You can do this with a simple bool instead of an int, but I like the counter approach so that I can keep incrementing codeChangingCount in nested calls and not accidentally reset it. In my production code, I have a class dedicated to this kind of flagging, and it (mis)uses IDisposable to decrement, so I can just wrap my calls in a using block, but the above snippet is simpler for illustration.
Check if Focused ListBox == ListBox2 and SelectedIndex > -1 then deselect Index[0]
if (ListBoxes[s] == sender && ListBoxes[s].Focused == true)
{
if(s == 1 && ListBoxes[s].SelectedIndex > -1) //assuming 1 is listbox2
{
ListBoxes[0].SelectedIndex = -1; // Deselect ListBox1
}
string msg = "sender is ListBox " + s.ToString() + "\nFocus is" + ListBoxes[s].Focused.ToString();
}
I am trying to get this while loop to keep playing a roulette game until my budget is empty. When I run the code it just hangs.
Here is the while code including the loop that hangs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPlay_Click(object sender, EventArgs e)
{
int Budget = Convert.ToInt32(txtMyBudget.Text);
int Bet = Convert.ToInt32(txtMyBet.Text);
int Outcome = Convert.ToInt32(txtMyNum.Text);
//generates a random number between 0 and 38
Random num = new Random();
int numSpun = num.Next(0, 38);
lblBudgetError.Text = numSpun.ToString();
//checks to make sure the budget is set
if (txtMyBudget.Text == "")
{
lblBudgetError.Text = "Please set your budget";
}
int myBudget = Budget;
while (Budget >= Bet)
{
myBudget++;
lblValidate.Text += myBudget.ToString() + "<br />";
if (numSpun == Outcome)
{
int newBudget = Bet * 35 + Budget;
txtMyBudget.Text = newBudget.ToString();
}
else
{
int newBudget = Budget - Bet;
txtMyBudget.Text = newBudget.ToString();
}
}
}
Thank you for your help.
You are changing the myBudget not Budget which is used in the loop. Either change the condition (use myBudget, like while (myBudget >= Bet)) or increase the Budget.
BTW, if you come from a background with two-way binding, it is not the case here, i.e., changing the value of the TextBox doesn't change the value of the Budget and you should update its value, for example in a getter.
I am aware of the question asked by user ElPeta. However the selected answer to his question does not fix my issue.
In my program I have a list box, whenever a check box is clicked and its checked property set to true, the list box is populated with text, however when the check box is unchecked, I want to remove the text associated with the check box from the list box.
Example Before and After:
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.Windows.Forms;
namespace CarFinderByMake
{
public partial class frmCFBM : Form
{
public frmCFBM()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'honestRalphsUsedCarsDataSet.tblCars' table. You can move, or remove it, as needed.
this.tblCarsTableAdapter.Fill(this.honestRalphsUsedCarsDataSet.tblCars);
}
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
//lstCarMakes.Items.Clear();
//populating the listbox
var fordCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Ford") select x;
foreach (var x in fordCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
else
{
for (int x = 0; x <= lstCarMakes.Items.Count; ++x )
{
//here I was attempting to find the index of the items...
if (lstCarMakes.Items.Contains("Ford"))
{
lstCarMakes.Items.IndexOf("Ford");
//and after that I was going to remove the items.
}
}
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
//lstCarMakes.Items.Clear();
//populating the list box
var cadillacCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Cadillac") select x;
foreach (var x in cadillacCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
}
}
}
The ListBox.ObjectCollection returned from ListBox.Items has methods Remove(obj) and RemoveAt(index). You can loop it backwards and use RemoveAt:
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
// you have it working ...
}
else
{
for (int x = lstCarMakes.Items.Count - 1; x >= 0; x-- )
{
string car = lstCarMakes.Items[x].ToString();
if(car.IndexOf("Ford", StringComparison.InvariantCultureIgnoreCase) >= 0)
lstCarMakes.Items.RemoveAt(x);
}
}
}
I have also used String.IndexOf instead of Contains to support case-insensitivity.
I don't know your specific error, but I imagine you might have an issue since you're using the item count of the listbox, and removing the items. When the item gets deleted the item count is changed. I believe there's a method for list box such as listbox.BeginUpdate() you can call before making changes to the items within the listbox and listbox.Update() after you're finished. Let me know if I'm in the right area with your problem