I am working a small sale invoice application on WF. I have a customer table and a product table. Then, I populate customer name and product name via comboboxes on Sale-form. Once user selects an item from ProductName combobox, other textboxes like Price and ProductID are auto-populated with data from Product Table from database. I have also a textbox named txtQuantity that can be entered for Quantity for product order. Once a number is entered for Quantity, subtotal, GST(which is Tax in Singapore), and total are auto-calculated and those values appear on textboxes of Subtotal, GST and Total. When a user delete quantity to update/change, it shows error as "Format Exception was unhanded, input string was not in a correct format". I like to prevent this error to stop working my application when user delete quantity or want to change to a new value. How do I go about it because I am complete lost here. Below is my code.
private void txtQuantity_TextChanged(object sender, EventArgs e)
{
int iQuantity = Convert.ToInt32(txtQuantity.Text);
decimal dPrice = Convert.ToDecimal(txtPrice.Text);
decimal dSubtotal = dPrice * iQuantity;
decimal dGST = dSubtotal * 7/100;
decimal dTotal = dSubtotal + dGST;
txtSubTotal.Text = Convert.ToString(dSubtotal);
txtGST.Text = Convert.ToString(dGST);
txtTotal.Text = Convert.ToString(dTotal);
}
I also wanted to set parameters for quantity textbox as only for entering numbers. I will do that later. This is going to be another thing to explore. Any advice for this is also welcomed and appreciated.
I would run all of your string inputs through the following (or something similar) before trying to assign them to an integer variable, especially when dealing with direct user input.
string myVar1;
//Something that assigns a value to myVar1
if(String.IsNullOrEmpty(myVar1))
{
myVar1 = "0";
}
else
{
int number;
bool result = Int32.TryParse(myVar1, out number);
if (result)
{
//you have a valid input and valid parse, do whatever you need with number variable
}
else
{
//bad input, reset to blank and show error message
}
}
Note the above code is an example and while fairly close to what you probably want, you will need to modify it before just copy/pasting it into your application
Related
I am pretty new to programming and have a C# Assignment for school. I have been searching for a couple hours now and I can't find a similar case that seems to address what I am trying to accomplish.
I have a windows form with 5 radio buttons. My assignment is to create a sales calculator using a switch statement to determine which radio button has been selected and based on the radio button selected get a sales total by multiplying the quantity of items sold by the price of each item and finally appending the result to a list box in dollar format.
Product 1 is $3.99 ea. and there are 5 products total.
Product 2 is $1.40 ea. etc. etc.
The first radio button is named RdbProduct1 and the Text for it is Product 1
I have this block of code. C# did not find any syntax errors, but the result is not being appended to the list box. Any help with this is appreciated, thank you.
private void BtnCalculate_Click(object sender, EventArgs e)
{
// Declare quantity variable convertted from Quantity text box
decimal quantity = Convert.ToDecimal(TxtQuanity.Text);
//Determine Product price using a Switch
//Calculate total sale by multiplying product price by quantity
//append result to list box
RadioButton radioBtn = this.Controls.OfType<RadioButton>()
.Where(x => x.Checked).FirstOrDefault();
if (radioBtn != null)
{
switch (radioBtn.Name)
{
case "Product 1":
decimal cost = 3.99m;
decimal subtotal = quantity * cost;
LstSuccess.Items.Add (subtotal.ToString("c"));
break;
}
}
}
To sum up the comments of the OP getting to the correct answer:
Solution is changing
switch (radioBtn.Name)
To
switch (radioBtn.Text)
Name is the name of the Control. Text is (in this case) what is displayed.
My task is to display a total when the user enters a quantity of their choice and multiply it by the price on an individual item.
The individual item price is held in an array of 5 and i am unsure how to multiply the price by a number entered inside a textbox?
Info :
Using Visual Studio, Windows Forms App .Net Framework
I need to display the total price of a car and multiple that by whatever quantity i enter into a different textbox.
Each vehicle has its own description,promo code and price within the array.
So what i am wondering is do i need to use the price set in the array for my calculation? or is there a much simpler way of doing it?
My attempt was using a simple if statement then multiplying the textbox by the prices set in the array.
Convert.To Double(textBox9.Text);
textBox17.Text = textBox9.Text * prices;
Please don't do string math. You need to develop a model ( a class ) that does the math for you, and your UI only displays the data.
public class CartItem
{
public decimal Price {get; set; }
public int Quantity {get; set; }
public decimal Cost { get { return Quantity*Price; } }
}
and on your UI you can do things like
CartItem item;
// .. fill data
if(int.TryParse(textBox9.Text, out int x))
{
item.Quantity = x;
}
textBox21.Text = item.Cost.ToString("c");
I am a new user in C# winform and also new user in this site, too
I have a datagridview with 4 columns
No. proname price qty total
1 fish 0.0 1 -
2 tofu 0.0 1 -
Data in example like that, I give the default price and qty like above total is empty. Now I need to cellclick on column price to new input value on currentrow after I gave the new value I leave it by press Enter key or anyway just leave the cell I need the price*qty = total on currentrow. Or opposite I new input the qty to 2... and price not "0.0" then Price * qty=total
But if I edit on other cell not two of above the event do nothing.
How do I multiply that ?
Anybody can help me in better solution?
Thank you in advance.
In the code Behind use this
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
Your Method look like this
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int quantity,rate;
if (int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value.ToString(), out quantity) && int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["rate"].Value.ToString(), out rate))
{
int price = quantity * rate;
dataGridView1.Rows[e.RowIndex].Cells["price"].Value = price.ToString();
}
}
For more find reference here
Another Reference
Here is exactly what you're looking for. Answer
The answer given by this guy is really well explained and it's not going to be hard doing the implementation.
By this way the "Total" column is automatically maintained via an
Expression which means you cannot manually do anything to that column.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I got 4 textboxes that I want to put values in, and I want it to find the average number from the values of the inputted values to the 4(or more) textboxes.
I want the average to display in a readonly box (is richtextbox good for this?).
You can use both a RichTextBox and normal TextBox for this. To ensure that it is read-only, in the designer page do the following;
Select the TextBox > Scroll under properties window > Behavior Section > Read-Only property
Setting this property to true will make the TextBox non-editable by the user.
After you have the 4 editable TextBoxes and 1 non-editable, you can implement something like the following to add up the numeric values of TextBoxes and display it in the readonly TextBox.
private void AverageAndDisplay()
{
try
{
//Convert values to numeric
decimal one = Convert.ToDecimal(textBox1.Text);
decimal two = Convert.ToDecimal(textBox2.Text);
decimal three = Convert.ToDecimal(textBox3.Text);
decimal four = Convert.ToDecimal(textBox4.Text);
//Find the average
decimal average = (one + two + three + four) / 4.0m;
//Show the average, after formatting the number as a two decimal string representation
textBox5.Text = string.Format("{0:0.00}", average);
}
catch(Exception e) //Converting to a number from a string can causes errors
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
So you should have this steps:
Create 4 textboxes. Let's this buttons has ID Value1Txt, Value2Txt, Value3Txt, Value4Txt
Add button with text Calculate Average Value. The ID of the button should be CalculateAverageBtn
Add the Label in which you will show the Average. The ID of this Label should be AverageValueLbl
Attach OnClick event on the CalculateAverageBtn. You could do it using the signature of the button OnClick="CalculateAverageBtn_Click" or doing it in the code
//this should be inside InitializeComponents method
CalculateAverageBtn.OnClick += CalculateAverageBtn_Click;
protected void CalculateAverageBtn_Click(object sender, EventArgs e)
{
//...code
}
Now in the body of CalculateAverageBtn_Click you should Parse the values of the TextBoxes and calculate the average. You could do this using decimal.TryParse method
decimal value1 = 0;
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
//if you come in this if the parsing of the value is not successful so
you need to show error message to the user. This happen when the user
enters text like 123Test, this is not a number. So you need to show
error message
}
Create a label in which you will show the error message. Let's call it ErrorLbl. So when the parsing is not successful we will write in this label the error message.
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
ErrorLbl.Text = "The value of value 1 textbox is not valid number"
return; //exit the button click method
}
Calculate the average of 4 textboxes and write it in the AverageValueLbl. This should be in button event click
AverageValueLbl.Text = (value1+value2+value3+valu4)/4.ToString();
Try to understand what you are doing, don't copy/paste mindlessly code. This is pretty much beginner programming. For sure this is homework, so try to understand it because in the future harder homeworks you will be lost.
Hi I am new to programming
I have a masked textbox into which a user inputs an account number, then I have a label which displays the number of users or rather display the number of times the account number has been changed. I.e. as each account number is being entered the customer count should increase.
I don't have an example code because I do not even know where to start
Please show me how to code this, I am using a form in Visual Studio
have it add the input to a list or array, and then you can run a check to see if the array/list contains that input already. If so, do not add the input again, if it does not, then add the input. You can then tell how many customers you have by the size of the list.
If you are taking in the users input as a string do a String Comparison or if you're doing strictly a numerical account number and am taking it in as an int then simply see if the numbers are different
For strings use:
result = input1.Equals(input2, StringComparison.OrdinalIgnoreCase);
For ints just use an If statement to test:
if(input1 != input2) {
Console.WriteLine("Input has changed")
else
Console.WriteLine("Input has not changed");
}
I'm guessing the user has to push a button after the user has entered the password? If so, we can easily track this. First we make a global int variable like so: private int userCount = 0;
Then we add an event to our button:
private void btnAccountNumber_Click(object sender, EventArgs e)
{
userCount = userCount + 1;
displayLabel.Text = userCount.ToString() + " Customers";
maskedTextBox.Clear();
}
So in this button we add our customer that just clicked on our button to the total of users.
Next we show that number in the label you created. And finally we clear the maskedTextBox of userInput so the next customer can use it.