Reno Jackins Reno Jackins - 3 months ago 17
C# Question

C# Variables are constantly re-assigned to inital values

I am fairly new to C# and am working on a group project, much of the code is not written by me. I am trying to create a user interface for collecting a range of data. After asking one questions, I want the next question to appear. I have done this by assigning a variable 'gesturenumber' and am increasing it when the user types 'next'. The problem is the value keeps returning to the initially defined value of one.

This is my initialization step at the start of this function:

public void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgse) enter code here{
int gesturenumber = 0;
int testnumber = 1;

if (e.KeyChar == (char)13)
int totalLines = richTextBox1.Lines.Length;
string lastLine = richTextBox1.Lines[totalLines - 2];
if (lastLine == "clear")
richTextBox1.AppendText("Welcome\n\nTo connect an IMU, please enter it's three digit ID number\n\nFor Assistance - Enter \"help\"\n\n", true);

When the user types 'collect' this value should change to 1, and when the user types 'next' it should increase by 1. The code I have written is below:

if (lastLine == "collect")

richTextBox1.AppendText("\nThank you for volunteering for our data collection process\n");
richTextBox1.AppendText("\nYou will be asked to carry out a series of gestures. Please repeat each gesture 10 times before moving on to the next.\n");
richTextBox1.AppendText("\nPlease choose which gesture number you will be doing'\n");
gesturenumber = 1;
testnumber = testnumber + 1;


if (lastLine == "next")
gesturenumber = gesturenumber + 1;
foreach (NU NU in ConnectedIMUS)
NU.saveData = false;
NU.Kat = false;

richTextBox1.AppendText("\n Thank you for completing the gesture, please follow the instructions for the next gesture \n", true);
catch (Exception) { }
richTextBox1.AppendText(" ", true);


Each part is contained in a separate if statement where the user input is read, or a certain variable is read.

When the function runs, the gesturenumber keeps resetting to zero, not allowing the if statements to be triggered. Please help me!


Your variables are reset every time the function runs, because you set their values within the function.

Instead, move them outside of the function, making them member-level fields:

private int gesturenumber = 0;
private int testnumber = 1;

public void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
    if (e.KeyChar == (char)13)