make a program run a number of times based on user input - c#

I have a windows form program that I would like to 'run' a certain number of times based on a number that the user specifies.
I am using Visual Studio 2013 and C#.
I have a program that has 16 picture boxes and randomly assigns pictures to 5 of these boxes. The person has to select the correct order of pictures. If they do, they are rewarded, if they choose wrong, they are punished by an annoying sound.
My first form has a TextBox that the user can specify the 'numberOfTrials'
I have a second form that takes the value of the TextBox and converts it into an int.
I want to have the main program on my second form run the number of times that the user specifies.
My program does work if I run it once, without using this variable.
I have tried using a for loop inside the method that starts the program, but this did not work. It just made all of the picture boxes white.
I then tried to use the for loop around the InitializeComponent() method but, again, this just made all of the picture boxes white.
My for loop uses the textbox variable as such:
for (int cycles = 0; cycles < numberOfTimesThrough; cycles++)
I create the numberOfTimesThrough variable by parsing the textbox variable.
Perhaps I am doing this wrong?
On the first form:
at the top of the class:
public static string trialNumberString;
inside a method that is called when a confirm button is pressed:
trialNumberString = tbTrialNumber.Text.ToString();
On the second form:
at the top of the class:
//Integer value for the string of trials
public static int numberOfTimesThrough;
bool canConvert = Int32.TryParse(Settings.trialNumberString, out numberOfTimesThrough);
Is this the correct way to get the string value of the textbox on the first form?
I am sure that adding a for loop should make the program repeat itself, so there must be something wrong with the way I am parsing the textbox string to an int.
The people using this program are not wanting to break it so the data entered into the textbox on the first form will always be between 1 and, say, 25. Do I still have to use a try catch around the string conversion?
Any help with this will be greatly appreciated.

You don't need to re-run the entire program just to show a form multiple times: instead, just instantiate multiple instances of the second form and show them in sequence.
To safely parse text as a number, you can use int.TryParse()

You can get the value of the textBox by accessing it's Text property and from there parse the string it returns to an int.
string s = textBox.Text;
int i = int.Parse(s);
Use whatever validation logic is necessary as well.

When application closes, static variables are deleted from memory too. In order to save setting, you need to save it to separate file and then read that. Simple way of read/write settings is using build-in options of ApplicationSettings: http://msdn.microsoft.com/en-us/library/vstudio/a65txexh(v=vs.100).aspx

Related

Android: How can I keep a record of the number of times an app was used?

I have a very simple app that creates a text file (after a button click) and sends it to a certain email address(after another button click). I want to add the ability to change the name of the text file that is created based on how many times the file was sent, or i.e. how many times the app successfully ran till the end. Currently, the name of the text file is fixed.
My idea:
I am thinking of adding a check on start-up of the app to see if another text file exists, lets called it Counter.txt. This will contain the number of times the 'send' button was clicked. If the file doesn't exist, then it will create it and append the number 0. Every time the 'send' button is clicked, it will open Counter.txt and increment that number. Also on a 'send' click, it will email the main textfile that I want to send and adjust the name by appending the number from Counter.txt to it.
I am not sure if this is the best or most efficient method, so would appreciate other suggestions to achieve this. Thanks.
Why not use SharedPreferences to store the number of times the app was launched and increment the value on the onCreate() method of your main Activity?
Then when the mail is sent, the file is renamed based on the SharedPreferences value.
I think it's better than changing the file name each time the app is started.
Here is a good Stack Overflow post on how to use SharedPreferences, you should check it out! There is also another post on how to rename a file here.
Hope this helps!
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. ~ Android Developer Documentation
// Create your shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// Write to shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("yourkey", yourvalue); // You could store the counter right here
editor.commit();
// Read from shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = 0;
int lastcounter = sharedPref.getInt("yourkey", defaultValue);

c# exception handling in textboxes

I am trying to figure out a solution in C# to perform exception handling for multiple textboxes using windows forms.
The user can only enter one or two positive integers in these textboxes and if the user tries to enter more numbers or letters, a tooltip should appear with a warning message?
Thanks for the assistance!
For a case like this, I like to do what I call "passive Error Reporting". Rather then throwing exceptions, you take every value (usually strings). But display a message if it does not fit some criteria.
The simple approach is INotifyDataError. It allows you to show one error for each property (it is advantagenous to use a property or a string key in the backend storage).
I know there is a more complex brother that allows Multiple errors per Property/Key. But it is too long since I read it's name, so I can not remember it.

Why can't this read integers from my text file? Sytem.FormatException

Okay, so I am making a game that reads data from a text file to create events. What happens is as each year advances if something exciting happens a popup box with three options appears, clicking them affects the game and so on.
I have created a function which can take various arguments and make the form automatically - so far so good- but writing large event descriptions in the code is messy and disorganized. Instead I decided to create another function which takes values from a text file, organizes them and then calls the second function to create the 'event'.
Now, as I said each event comes with three choices (See below) and each choice has a consequence on one of three factors (approval, prestige, power), I haven't quite worked out the mechanics properly but all in good time, everything runs wonderfully until I need to load this integers from the text file.
It keeps having trouble converting the string to an integer, why is this and how can I fix it?
Line 11 of the text file: 10 (yes I checked and it is the right line to read)
The code:
List<int> affecta = new List<int>();
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Take(11).First()))
I can load the other things such as the picture file's location perfectly, so 'filename' points to the correct .txt
It might be something really obvious to someone with more experience, but I just can't see why.
I don't think Take does what you think - It grabs the first 11 items and returns all of them, so you get an IEnumerable of 11 items. When you do First on that, you get item at position 0, not position 10. I think you want Skip and then First, which will skip the first 10 items and return the next (11th) item:
affecta.Add(Int31.Parse(System.IO.File.ReadLines(filename).Skip(10).First()))
If you use Take(11) this means "get 11 rows from the source". After that you have First(), so you'll get first of them. You're essentially trying to convert the first line into integer.
I assume you want to use Skip(10) since you want the 11th line.
Take(11).First() returns the First element from the IEnumerable containing the 11 elements.
Instead, Skip the first 10 and select the First from the IEnumerable.
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Skip(10).First()))
Alternatively, Take the first 11 and select the Last from the IEnumerable.
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Take(11).Last()))

Converting TextBox number to the integer

I'm new to C# and i'm doing this just for practice (this isn't homework)
Okay so I need to convert a text box text (called Numbers) into an integer
I tried something like:
int number1;
number1 = int.Parse(Numbers.Text);
Then to check if it's right:
label1.Text = number1.ToString();
MessageBox.Show(number1.ToString());
But integer doesn't hold anything. I get no Message and the label doesn't change.
Additional question:
Why doesn't the message box doesn't show?
There were no if statements either switches.
When it comes to user input and parsing, you may want to try Int32.TryParse. if gives you the ability to parse, but also that secondary feedback letting you know if it was a success or not. For example:
Int32 parsed;
String input = "3";
if (Int32.TryParse(input, out parsed)){
// it was successful and `parsed` = 3
} else {
// `input` most likely had something invalid
}
I have verified your code, and what you have posted is fine.
I assume your problem is the code isn't being ran. Make sure the method is being called.
If you can't fix it still, add a new button on the form. Double click on the button, and add that code to the method that is automatically created.
Then test it by clicking on the button at runtime.
This is pretty basic stuff and should work. Considering that the MessageBox doesn't appear at all, I guess you need to clean your build. Either choose Clean from Solution's context menu, or close the solution and VS, go to project directory, remove bin and obj and come back and rebuild the project.
Here is a simple method
int i;
try
{
i=Convert.ToInt32(textBox1.Text);
}
catch
{
//do whatever you want
}

Create CMD-like arguments for SendKeys

I'm currently working on a Program, that presses buttons for me. I'm working on WPF but I already finished my design in XAML, now I need some C# code.
I have a TextBox that should handle all the SendKeys input. I want to extend it's functionality by providing some CMD-like arguments. The problem is, I don't know how. ;A; For example:
W{hold:500}{wait:100}{ENTER}
This is a example line that I'd enter in the textbox. I need 2 new functions, hold and wait.
The hold function presses and holds the previous key for the specified time (500 ms) and then releases the button.
The wait function waits the specified time (100ms).
I know I could somehow manage to create this function but it would end up being not user editable. That's why I need these arguments.
You're trying to 'parse' the text in the text box. The simplest way is to read each character in the text, one by one, and look for '{'. Once found, everything after that up until the '}' is the command. You can then do the same for that extracted command, splitting it at the ':' to get the parameters to the command. Everything not within a '{}' is then a literal key you send.
There are far more sophisticated ways of writing parsers, but for what it sounds like you are doing, the above would be a good first step to get you familiar with processing text.

Categories