Storing value from try for use in second try C# - c#

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
{
}

Related

How to execute a method with a button click

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.

Basic C# WPF Program - Converting string to double then adding variables in Textblock

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.

Addition in Button Event C#

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.

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?

files in C# - "file is used by another process"

I have following code:
private void askforlocation()
{
if (File.Exists("location.txt"))
{
System.IO.StreamReader loc = new System.IO.StreamReader("location.txt");
string loca = loc.ReadToEnd();
if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}
else
{
label6.Text = "Please select the location!";
}
loc.Close();
}
else label6.Text = "Please select the location!";
}
It is supposed to read value "location" from the file and put it to the combo box, which works ok.
I run this script on Form1_Load.
Now, I have another script:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = comboBox1.SelectedItem.ToString();
System.IO.File.WriteAllText("location.txt", value);
}
This one is supposed to record the choice so that user doesn't need to enter location every time.
What is happening is when I start a program, so the value is already set, then I try to change it (so that theoretically it should overwrite the previous one), but I get an exception, saying that file is already being used by another process.
I do close the file after I used it. I also tried FILE.DISPOSE.
What am I doing wrong?
I think what's happening here is that this code:
if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}
is causing the SelectedIndexChanged event to be raised on the combobox. When that event is raised, comboBox1_SelectedIndexChanged is called, and that method again tries to access location.txt.
To fix, I would first change the code in askforlocation to something like this:
if (File.Exists("location.txt"))
{
var loca = string.Emtpy;
using(var loc = new System.IO.StreamReader("location.txt"))
{
loca = loc.ReadToEnd();
}
....
}
since there's no need to keep the file open for longer than necessary (note that the using block will call the Dispose() method on the StreamReader when it exits, which in turn will call the Close() method). After that, I'd consider coming up with a way to keep the event from being fired when you set the selected index on the combobox (maybe use a flag or unwire/rewire the event handler).
It seems that you're changing the index of your combobox, thus writing to the same file before closing it. Call loca.Close() before writing to the file again.
comboBox1.SelectedIndex = index;
this will fire the event SelectedIndexChanged, so invoke the Close() method right behind ReadToEnd():
private void askforlocation()
{
if (File.Exists("location.txt"))
{
System.IO.StreamReader loc = new System.IO.StreamReader("location.txt");
string loca = loc.ReadToEnd();
loc.Close();//move that code to here
if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}
else
{
label6.Text = "Please select the location!";
}
//loc.Close();
}
else label6.Text = "Please select the location!";
}
Give this line loc.Close(); before setting the index of the combo box because the event is being raised earlier than you think.
You never need to call file.Close() or file.Dispose().
Please use a using statement ALWAYS (or mostly) when using a class that implements IDisposable. It will call the Dispose method for you.
using(System.IO.StreamReader loc = new System.IO.StreamReader("location.txt"))
{
string loca = loc.ReadToEnd();
}

Categories

Resources