private void button2_Click(object sender, EventArgs e)
{
int a,sum=0;
a = 10;
sum = sum + a;
MessageBox.Show( sum + "Sum Result");
}
Every time I click on the button I get the answer 10. I want to store result. Suppose I click 5 times then there should be 50.The above code for better understanding should give you some idea of what I'm going for.
Other option if possible I get this result outside of the button event by some method. I am new in C# so feeling lot of problem.
As #tnw tried to tell you - move sum outside the function like this:
private sum = 0;
private void button2_Click(object sender, EventArgs e)
{
sum = sum + 10;
MessageBox.Show( sum + "Sum Result");
}
This should work
explanation
The problem you face is that every variable declared inside a function will get initialized every time you call this function and is discarded when you exit the function.
With the variable beeing outside you made it a field of your class and it will be kept in memory as long as the instance you are using (for example the instance of your form) will be.
It is because sum=0; gets re-initialized every time you call the function. Try setting it as a global variable inside the Class and then call it.
This way, when ever the function will be called, the value of sum won't get back to 0, but will increment from where it was left.
// somewhere above
int sum = 0;
// then the function
private void button2_Click(object sender, EventArgs e)
{
sum = sum + 10;
MessageBox.Show(sum + " = Sum Result");
}
..since you're not using a or b. I have removed them. However, if you're using them inside the function (in a code which you haven't posted) please add them back.
Each time you called the function, you created new variable called sum and if gets deleted at the end of the function. So, each time you pressed the button, sum had a value of 0 in it as initially. Adding 10 to it, would always return 10.
Global variables are declared inside the class itself. Every variable inside the function (such as this one) would be recreated each time you call the function and will have the value you're providing it with. So it is a better approach to write the variables globally, whose value is required next time.
Related
How can I add a function to a button that will run a method I've created. I want to write out an array into a message dialog box with a press of a button, but I don't seem to be getting anywhere so i turned to stackoverflow for some help, since googling didn't really help me with my problem.
static void Tractors(Tractor[] tractors)
{
for (int i = 0; i < tractors.Length; i++)
{
Console.WriteLine((i + 1) + ", " + tractors[i].ToString());
}
}
This is my function that writes out the table of "Tractors".
private void button1_Click(object sender, EventArgs e)
{
}
What should I write into the button1_click method so that it would work?
You need to bind the event handler with the button control and write the logic inside this event handler. If its windows form application you can do like this.
this.button1 = new System.Windows.Forms.Button();
this.button1.Click += new System.EventHandler(this.button1_Click);
private void button1_Click(object sender, EventArgs e)
{
//Call your methods here
}
You would call Tractor() the exactly same way you call Console.WriteLine(). Both are static functions.
However the function is utterly messed up and propably not salvageable. The proper name would be printTractorsToConsole(). As it contains the Console.WriteLine() call, it is strongly tied to Console Applications - avoid tying functions to one Display Technology like that.
You need a more general function that creates and returns a string. You can then send that string to WriteLine(), assign it to Label.Text or wherever else you want the string to be. Strings primarily exist for intput from or output towards the user - and there is too many ways to get it to them.
//Not tested against a compiler, may contain syntax errors
static string TractorArrayToString(Tractor[] tractors){
string output = "";
for (int i = 0; i < tractors.Length; i++)
{
output += (i + 1) + ", " + tractors[i].ToString()) + Environment.NewLine;
}
return output;
}
But even function might be a bad idea, as that function would tie all representations to a single format. Generally you would write that loop directly into the Click Event. But this function looks like it is for printing for debug purposes, so it might work.
Good day fellow helpers, i have following problem:
(running MS Visual Community Edition 2015)
private void button4_Click(object sender, EventArgs e) // Senden
{
serialPort2.WriteLine("SR,00,002\r\n");
textBox1.Text = "gesendet";
textBox3.Text = "";
try
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\blub.txt");
String line = file.ReadToEnd();
string Hallo = line; \\in the beginning there is "0" in the file
file.Close();
decimal counter = Convert.ToDecimal(Hallo); \\just for testing
counter++;
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,"); \\cuts off unwanted input from device
decimal b2 = decimal.Parse(b1[1]); \\number like -3000
System.IO.StreamWriter test = new System.IO.StreamWriter("C:\\blub.txt");
test.WriteLine(counter);
test.Close();
textBox7.Text = "Das ist counter:" + counter;
}
catch (TimeoutException)
{
textBox3.Text = "Timeout";
throw;
}
}
Now, the Serialport is a device that returns a lengthmeasurment. As it is a bit weird, or just the way its build it start with a negitve number (between -5000 and -3370). Now as i want to get measurement on the screen that is realistic i want to set the value to 0 and calculate the difference.
Means: I start the programm - press send - get a value (say -3000) - press send again (after pushing the seonsor in) and get the value that its been pushed in > 0 by adding the difference to 0.
I only learned to store values externally when i had a C course a year back like i did within my programm. Is there a way to store the value from the first measurement in the programm so i can use it on the next send/try?
The counter was just for testing and I would exchange it for the "decimal b2"
I hope there is an easy fix for that, not really a pro with C# yet but i'm eager to learn. I thank the willing helpers in advance, MfG, Chris
OK, I will simplify this in order to show concept so it will not have all the code you are actually using.
So, what you want is to click on button, get some values and store them for next click.
Value is stored in variable. If you have variable in function that is handler for click event, as soon as function completes execution, value will be destroyed.
So, what you need is to create variable in outer scope (class level). Your function is already in class of the form so let's get to code:
class Form1
{
string BetweenClickStorage;
private void button4_Click(object sender, EventArgs e)
{
//Load data here
BetweenClickStorage = LoadedData;
}
}
After this, when you click again on the button, value will still be in BetweenClickStorage. It will be also available to all other buttons click handlers and other code in that form.
If I'm understanding your question correctly, the answer is simply to declare a variable outside the try/catch:
//declare variable //
var measurement;
// TRY #1 //
try
{
//assign value to the variable here
}
catch
{
}
// TRY #2 //
try
{
// reference variable here
}
catch
{
}
Good evening all,
I've just started my second year at University and I'm learning C# for the first time. I've had some coding experience with Java and Javascript before but never c#.
I'm having problems with a basic credit/debit program. See code below:
private double balance = 0;
private string creditamount;
private string debitamount;
private double currentamount = 0;
private void CreditButton_Click(object sender, RoutedEventArgs e)
{
AmountField.Text = creditamount;
Convert.ToDouble(creditamount);
CurrentBalance.Text = "Your current balance is £" + (creditamount + balance);
}
private void DebitButton_Click(object sender, RoutedEventArgs e)
{
AmountField.Text = debitamount;
double.Parse(debitamount);
CurrentBalance.Text = "Your current balance is £" + (debitamount - balance);
}
The user should enter an amount into the AmountField and press either the Credit or Debit button. Upon clicking either button, the amount should be converted from a string into a double and then shown in the CurrrentBalance .Text
It apppears that my strings aren't being converted into doubles.
I've tried using Convert.ToDouble(); and double.Parse(); but Visual Studio keeps giving me errors.
Does anyone have any suggestions?
The = assignment goes from Right to Left. Also all Convert.ToStuff return the result, so you should be expecting it (assign it to some variable).
Therefore, your event handlers (and all your future routine) should look similar to this:
private void DebitButton_Click(object sender, RoutedEventArgs e)
{
debitamount= AmountField.Text ; // Take the Right and assign it to the Left
currentamount = Convert.ToDouble(debitamount); // convert + assign
CurrentBalance.Text = "Your current balance is £" + (debitamount - balance); // Again take the Right and assign it to the Left
}
First of all if you are using wpf try to avoid this code behind thing. Secondly try to take advantage of MVVM. What is MVVM. Go through this link.
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
So in short i would suggest create a Viewmodel class and make it implement INotifyPropertyChanged. Create your credit and debit amount properties bind it in the UI and don't forget to use OnPropertyChanged on these properties. So when ever user enters any text in the UI i.e when ever there is a change in the UI state your set block of the variables will be called and you can proceed further. Also in mvvm you use commands not button clicks. Also set the data context of you xaml to this view model.
I am creating a windows form that is a random number guessing game. I've made these before in C++ and never had an issue, however I have a big one here- I have no idea how to get the user back to input a number after the loop has began running. Here is my code:
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = 0;
int count = 0;
int accumulator = 0; // accumulator
Random rand = new Random();
int number = rand.Next(1, 100);
txtAnswer.Focus();
while (guess != number)
{
guess = int.Parse(txtAnswer.Text);
if (guess < number)
{
MessageBox.Show("Too Low! Guess again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else if (guess > number)
{
MessageBox.Show("Too High! Try again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else
{
MessageBox.Show("Correct! you guessed the number in " + accumulator + " tries!");
break;
}
}
}
}
}
I just filled the while loop arguments with something for you guys, even though i know it won't work. Basically, I need to run the loop, get feedback (if the users guess was too high or low) then get the user to be able to input another number BEFORE the loop runs again. I don't know how to get that to happen with a text box control which is where the input will be. Any ideas?
You should not loop inside in the btnGuess_Click. Instead you need to store the state (the number, count, and the accumulator variables) in the scope of the form itself.
Initialize the random number when the form loads, or using some kind of start button.
Then inside the guess button handler, read the text box value and compare it to the number variable, such as what you are doing currently.
What you are building is more a console style application. So there is 1 main loop that is executing all the code.
In forms applications it is an event driven environment. So the user gets a form, presses a button, the form is evaluated and then the method handling ends.
So you have on a class level some variables for counts, in the constructor you add the initialization and the method for submit will be something like
private void btnGuess_Click(object sender, EventArgs e)
{
//Increment counters
//Check
//Show feedback
//Leave the button click code
}
For some more info, check this out:
https://msdn.microsoft.com/en-us/library/dd492132.aspx
I have a system timer firing an event every 10 seconds. So every 10 seconds I call the class "Termocoppia" from the main thread of the form transferring the value of "milliV" to it and expecting to get back the value of variable "tempEx".
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Tick += OnTimerTick;
timer.Interval = 10000;
timer.Start();
}
double tempEx;
//here a call the method "Calcola" in the class "Termocoppia"
private void OnTimerTick(object sender, EventArgs e)
{
double milliV = Convert.ToDouble(textBox8.Text); //I have a value of 1.111
Termocoppia thm = new Termocoppia();
thm.Calcola(milliV, tempEx);
textBox7.Text = tempEx.ToString();
}
the value milliV is then transferred to the method "Calcola" inside the class "Termocoppia". I debugged it with a break point and I confirm that the value is received in the class.
The class "Termocoppia" is like this:
public class Termocoppia
{
public double Calcola(double milliV, double tempEx)//here the value of milliV is still 1.111
{
tempEx= milliV;//here the value of tempEx is 0???
return tempEx;
}
}
I expect to receive back exactly the same value sent to the class that is well received but I keep getting back 0.
If I debug the variable tempEx at the line "tempEx=milliV" the value of tempEx is 0 and I do not understand why? I am quite sure I am doing a beginner mistake here but I cannot come right with this problem.
You have two variables called 'tempEx', a field and a parameter. Your Calcola function modifies the tempEx parameter (not the field) and returns the same value. But the caller is not doing anything with the returned value. My suggestion is to two this value into the field tempEx.
Modify your line:
thm.Calcola(milliV, tempEx);
into:
tempEx = thm.Calcola(milliV, tempEx);
A suggestion: Use a coding standard to prevent this kind of mistakes. For parameters use camelCasing (so tempEx), for fields use an underscore (_tempEx).
You are not using the return value from Termocoppia.Calcola.
private void OnTimerTick(object sender, EventArgs e)
{
double milliV = Convert.ToDouble(textBox8.Text); //I have a value of 1.111
Termocoppia thm = new Termocoppia();
// the return value from Cacola has to be assigned to tempEx
tempEx = thm.Calcola(milliV, tempEx);
textBox7.Text = tempEx.ToString();
}
You should not use the same variable names for tempEx as member variable and method parameter!