c# when pressing a button add totals together [closed] - c#

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 6 years ago.
Improve this question
When i press "buttonTotal" i need it to add fuel prices together. I have lblDailyPrice, lblTotalLitresEntered and i have 3 buttons "unleaded"; "Diesel"; "Premium"... any help as to how i can achieve this?
private void btnTotal_Click(object sender, EventArgs e)
{
try
{
if(btnUnleaded_Click)
{
}
else if (btnDiesel_Click)
{
}
else if (btnPremium_Click)
{
}
}
catch
{
}
}

I would advise making the "unleaded", "Diesel", "Premium" options RadioButtons instead of Buttons and bind them under a container like Panel. So, when the user presses the "buttonTotal" the program will check which RadioButton is checked and then calculate the corresponding value.
private void btnTotal_Click(object sender, EventArgs e)
{
double totalPrice = 0;
if(unleadedRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * unleadedValue;
}
else if (dieselRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * dieselValue;
}
else if (premiumRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * premiumValue;
}
}

I'm assuming your using Windows Forms. I have linked relevant documentation on how to accomplish this task. With just a tiny bit of reading, it should be easy. Good luck and welcome to StackOverflow!.
Get the prices from the labels.
Convert those strings into a number type with a decimal.
Then just do the math on the resulting variables.
Example:
var total = Convert.ToDecimal(lblDailyPrice.Text) * Convert.ToDecimal(lblTotalLitresEntered.Text);

Related

Capturing return value from helper class c# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've spent the better part of an hour reading over linked items on Google about this topic; however, maybe it just is not sinking in. What do I need to do to capture the return value from a helper class in C#? This is the code:
protected void Page_Load(object sender, EventArgs e)
{
HelperClass.Calculate(a, b);
}
public static string Calculate(string a, string b)
{
string value = string.Empty;
// inner code workings
return value;
}
I know I'm missing something but I cannot for the life of me determine what. Any help would be appreciated! Thank you!
var x = HelperClass.Calculate(a, b);
Just like any other function, which returns a value?
protected void Page_Load(object sender, EventArgs e)
{
string value = HelperClass.Calculate(a, b);
}
public static string Calculate(string a, string b)
{
string value = string.Empty;
// inner code workings
return value;
}

The Code Won't Execute all [closed]

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 have the following code:
private void G1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, cost = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Cost"].Value.ToString(), out cost))
{
decimal price = quantity * cost;
G1.Rows[e.RowIndex].Cells["Total"].Value = price.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity))
{
newtotalstock = totalstock - quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
return;
}
decimal avai = 0, newavai = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai - quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
return;
} }
The problem is, it only execute 2 out of 3 the code, I mean, when the newtotalstock is calculated, the code will end.
I try to change the newavai to up above, and the result is the same, it will calculate the newavai and pass the newtotalstock. I dont know why, all the code are correct. Please help
word "return" ends function, if you are using void type method you don't really need to use return, unless you want to quit it at certain point. The code after "return" will never be executed (only exception might be during usage "yield return", but that is another story).
void someMethod()
{
doSomething();
return;
StartWorldWarThree(); //no waries, this will never be executed :)
}
Furethermore you can always make a breakpoint in your code (click on the left border of your window, or just read about it) and then check how your code is being executed :) F10/F11 to make step in your code, F5 to go to next breakpoint or end execution, if there are no more breakpoints.
Taking in count that all conditions are true the return; will stop executing the rest of the code, if you want the 3 if to be executed, remove the return; and place it the last line of the method as
void Method() {
if() {}
if() {}
if() {}
return;
}
Or dont place it at all, because that method is void and does not need it

Matching brackets and indentation in RichTextBox using C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a Code Editing control that can format text somewhat like Visual Studio,till now i have implemented syntax highlighting and autocompletion but i want to format text in nested curly braces.For example:Consider a for loop,
for(int i=0;i<=10;i++)
{
Function_One(); //This should be a tab away from first brace
Function_Two(); //So with this
if(a==b) //So with this
{ //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
} //This should be four tabs away from first brace
}
now what i want is that this should look something like this,
for(int i=0;i<=10;i++)
{
Function_One();
Function_Two();
if(a==b)
{
MessageBox.Show("Some text");
}
}
I have already tried Regular Expressions but at some point they fail to match,so i tried to match it with code but code cannot match very deeply nested code or is very hard to implement
,so is there any way to achieve this,and one more thing i am doing all this in Winforms control RichTextBox using C#.
This is by no means a simple feat, I am unaware of any tools or plugins that you would be able to take advantage of, my only recommendation is to research Monodevelop's implementation of this.
See MonoDevelop's github for details.
I think the best way to implement this would be to create some global variables for your form:
private int _nestedBracketCount = 0;
private const string TabString = " ";
private const int TabSpaces = 4;
And then handle all of it in a KeyPressed event handler for the rich text box:
private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
var currentLength = richTextBox1.Text.Length;
if (e.KeyChar == '{') {
// need to increment bracket counter
_nestedBracketCount++;
} else if (e.KeyChar == '}') {
// remove last #(TabSpaces) characters from the richtextbox
richTextBox1.Text.Remove(currentLength - TabSpaces);
_nestedBracketCount--;
richTextBox1.AppendText("}");
e.Handled = true;
} else if (e.KeyChar == (char)13) {
// append newline and correct number of tabs.
var formattedSpaces = string.Empty;
for (var i = 0; i < _nestedBracketCount; i++)
formattedSpaces += TabString;
richTextBox1.AppendText("\n" + formattedSpaces);
e.Handled = true;
}
}
I think this should provide you with a halfway decent starting point.

C# textbox user input processed by a button object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button
This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# and I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys. Thanks for all of the advice guys.
I'm using Microsoft Visual Studio 2010 in C# language. I'm using Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
As a couple of comments have mentioned, there really isn't enough information here to provide you with a useful answer. There are two main User Interface frameworks in .Net for windows applications. One of these is commonly referred to as "WinForms" and the other is "WPF" or "Windows Presentation Foundation."
I'm going to go with you are most likely using WinForms as it is the older of the two technologies. The approach here can be used on both sides with a little tweaking. Setting text in a text box is very similar to setting text programaticly on a label. You can get more detail on that on MSDN: How to: Display Text on a Windows Form; How to: Use TextBox Controls to Get User Input.
If you are using WPF the "back end" code is pretty much the same. You just need to make sure your textbox has an x:Name="userInputTextBox" so you can reference it in your code behind. Be mindful that your users can input "1", "3" or "abcd" in the field. Ensuring your app doesn't bomb is most likely outside of the assignment but feel free to look up C# int.TryParse(...) and "Try Catch" :-)
Your button handler could look like this:
void btnUserClick_Click(object sender, System.EventArgs e)
{
int userValue;
if(int.TryParse(txtUserInput.Text, out userValue))
{
// We have the value successfully, do calculation
}
else
{
// We don't have the users value.
MessageBox.Show("Please enter a valid integer into the text box.")
}
}
In your retrieveInput_Click handler you are assigning the min/max numbers to a local int. Once you determine your min/max numbers in the logic, you will need to assign those local integers to a UI element for display.
Since we don't have any details on your specific UI choices, one simple solution could be to add 2 labels to your form, and then in the code you would place the result in the label:
for (int i = 0; i < numbers.Length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
if (numbers[i] > max)
max = numbers[i];
}
// Assign Minimum to Label1
Label1.Text = "Minimum Value: " + min.ToString();
// Assign Maximum to Label2
Label2.Text = "Maximum Value: " + max.ToString();
define the textbox named textbox1 or txt_name
you can write the button1_Click function :
int i_value = Convert.ToInt16(txt_name.Text);
ok. I haven't try catch the exceptions.... :(
maybe above answer is right.
btw, i think this question mainly focus on how to get int type from text box. right?

seeking help for Object Clone [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
class Puzzle
{
public int PUZZLESIZE = 3;
public int numSteps = 0;
public Button[,] buttons;
public Puzzle(Form1 form1)
{
buttons = new Button[3, 3] { { form1.button1, form1.button2, form1.button3 },
{ form1.button4, form1.button5, form1.button6 },
{ form1.button7, form1.button8, form1.button9 } };
}
public Puzzle Clone()
{
return (Puzzle)this.MemberwiseClone();
}
public void reset()
{
//reset all 9 buttons color
}
public void flipcells()
{
//flip cells in the puzzle with color change
}
class Undo
{
Puzzle newPuzzle; //null value here. Why???
public Undo(Puzzle oldPuzzle)
{
Puzzle newPuzzle = oldPuzzle.Clone();
}
public void undo()
{
//back to previous step, ie the color of the buttons go back to previous color
}
I'm asking to do the undo function for back to previous stages for max four times. "The easiest way to do this is to create a copy of the puzzle and store it in an array of Puzzle. To do this I implemented a Clone method for puzzle. This returns a brand new puzzle set to exactly the same settings as the puzzle that I called Clone on." This is what our instructor says, but i still have no idea of how to implement this.
The easiest way to implement your "Undo" function would probably be with a stack. For each action you take on the puzzle, push an instance onto the stack. When the user opts to undo a move, pop the instance off of the stack.
See this article on Wikipedia for more information on stacks, and this MSDN article on the .NET Stack generic class.
Here's a little example of how to implement the stack mentioned by DBM. In stead of cloning the whole Puzzle class, I would recommend to rather just clone the array of Buttons (that should be enough for your Undo function):
Edit: If you need to keep track of the colors of the buttons in stead of the position of the buttons, you could probably rather just put an array of the buttons' current colors on the stack.
Stack<Button[,]> stack = new Stack<Button[,]>();
private void button4_Click(object sender, EventArgs e)
{
Button[,] buttons = new Button[2, 2] { { button1, button2 }, { button3, button4 } };
stack.Push((Button[,])buttons.Clone());
buttons[0, 0] = button2;
buttons[0, 1] = button1;
stack.Push((Button[,])buttons.Clone());
buttons[1, 0] = button4;
buttons[1, 1] = button3;
stack.Push((Button[,])buttons.Clone());
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (stack.Count > 0)
{
Button[,] buttons = stack.Pop();
txtButtonOrder.Text = buttons[0, 0].Text + buttons[0, 1].Text + buttons[1, 0].Text + buttons[1, 1].Text;
}
else
{
timer1.Enabled = false;
}
}
When you declare a variable inside a method, it will hide any variables in the class which have the same name. Instead of redeclaring the variable, you should just reference it:
int myVariable = 0; // Will always be 0
public void SetMyVariable()
{
int myVariable = 5; // Isn't the same as above
}
If you want to be explicit, you can add 'this.' in front of the variable name to always refer to the class variable:
this.myVariable = 5;

Categories

Resources