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
}
Related
Basically I am working on a project which is very much similar to inventory management system. Uptill now I have made users form, category form and I was working on products form when this error came I have tried different methods but none of them seems to work.
In all the forms I am using stored procedures and some classes like insertion to add,updation to update,deletion to delete and retrieval to view the data.The exception comes to be "input string is not in correct format" Need help!
Insertion.insertProductItem=(pitemtext.Text, Convert.ToSingle(priceTxt.Text),Convert.ToInt32(catDD.SelectedValue.ToString()),status)
Most probably the error message is coming from Convert.ToSingle(priceTxt.Text) or from Convert.ToInt32(catDD.SelectedValue.ToString().
This error message simply means that the string you are trying to convert into int or single doesn't contain a valid string that can be converted to int or single. For example, following code will issue Input string is not in a correct format exception.
int foo = Convert.ToInt32(" "); //or even null
int foo = Convert.ToInt32("5p");
//and there can be many such cases. Browse the last link at the bottom.
I would suggest, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception and you can simply write an if statement to see if it works or not. Like,
int foo = 0;
if(int.TryParse(textBox1.Text,out foo))
You can even use Single.TryParse() method, read here
Now one last thing. This exception could also be thrown when you try to Convert.ToSingle() value that does not belong to the CurrentCulture. So you could instead use Convert.ToSingle(String, IFormatProvider). You can read more here.
A similar question has been asked earlier that can be helpful. Read here.
I need a Text field of my program to be treated as a LONG type variable and be processed in a mathematical operation. The value of this variable needs to be specified every time by the user and I want the program to treat this value not as an integer but as a long indeed.
I have treated other fields as integer and they work fine with this kind of code:
HourField.IntValue
now notice that .IntValue that obviously says to the program to take the content of the HourField whatever is in it and treat it as an integer.
But unfortunately there is no equivalent for the long type in fact if I try to write .LongValue, C# just doesn't recognise this function....there are other similar functions like .FloatValue or .DoubleValue etc. but there is no such thing as .LongValue.
However I even tried to use this kind of syntax:
Convert.ToInt64(FileSizeBytesField);
or something like that and in theory the compiler doesn't give me any error for the compilation etc. but if I try to actually make the calculation by pressing the button the program crashes and Visual Studio tells me that the type of casting is invalid.
Please please pease help me with this. It's the last thing I need to actually finish my program!!!
P.s. I am posting some screenshots of what I got and of my source code. Thanks
program's source code
Debugging error in Visual Studio after program crash
I guess the FileSizeBytesField you are trying to take a value from is an instance of NSTextField or another subclass of NSControl. In that case, you can take the value of control using properties like IntValue or StringValue. So, to convert the value to long type try this:
Convert.ToInt64(FileSizeBytesField.StringValue)
Or, using more common approach already suggested by Hooman Bahreini:
long fileSizeBytes;
if (long.TryParse(FileSizeBytesField.StringValue, out fileSizeBytes))
{
// use fileSizeBytes
}
You can use Parse, to convert the string value to long
long l = long.Parse("453216");
If you want to ensure that your input is a valid number, you can use tryParse
if (long.TryParse("45263572", out l) == true)
{
// use long value
}
else
{
// input is not a valid long value... handle the situation here
}
So, working in C#. I have a CSS-based drop-down menu. I open the menu, then grab a reference to it using FindElement by CSSSelector. I then grab the contents of the list using FindElements, again by CSSSelector.
Now here's where it get's interesting. I iterate the list, based on a file I have open in a streamreader.
Looks something like:
list = driver.FindElement(By.CSSSelector("dropdown-menu"));
list_items = list.FindElements(By.CSSSelector("LI > A"));
int row = 0;
while (data_file.read())
{
iWebElement item = list_items[row];
string label = item.text;
string url = item.getattribute("href");
assert.areequal("something", label);
assert.areequal("something else", url);
row++;
}
Now here's the thing: if the mouse pointer is placed over the drop-down, while this is executing, item.text returns value and the test succeeds. If the pointer is anywhere else, item.text will be blank and the test fails. Trying to understand what's going on, and taking a clue from the fact that though the test would fail when running, but would succeed while stepping, I modified the code with a loop:
while (data_file.read())
{
iWebElement item = list_items[row];
string label = item.text;
while (label == "")
{
label = item.text;
}
string url = item.getattribute("href");
assert.areequal("something", label);
assert.areequal("something else", url);
row++;
}
Now the test will always succeed, but if the pointer is not on the control it is SIGNIFICANTLY slower... we're talking a factor of 4 or 5... then when the pointer IS on the control. By wrapping a timer around this, I find that it typically takes between 2 and 4 seconds before .text returns anything but an empty string... sometimes longer.
Again, this delay only seems to apply when the mouse pointer is not over the drop-down. Otherwise, the value appears to be there instantaneously.
Can anyone suggest a possible explanation for why it's behaving this way, and a possible approach to solving it?
BTW, I'm not finding any difference between:
item = list_items[row];
label = item.text;
and
label = list_items[row].text;
Nor does .getattribute("value") produce any faster results than .text.
As for why the menus are acting this way, it's hard to tell with the code you've provided. If you could provide the code that displays your menu, that might help. As for solutions, there are a couple.
The label could be taking longer to display because of the while loop itself - it's just going crazy grabbing the text over and over very quickly. A better solution would be to wait for the element to be present. This may make your code run faster. See the Selenium Website for information on using WebDriverWait.
Alternatively, there is an "ugly" solution. You can just move the mouse to the menu with Selenium, to make sure the menu is always displayed when you need it. I've adapted some code from here as an example:
OpenQA.Selenium.Interactions.Actions builder = new
builder.MoveToElement(list).Build().Perform();
Hope this helps!
I'm almost finished writing a small add-on for League of Legends that allows players to click a checkbox in my form, and the checkbox's function clicks in the search bar (which automatically clears it. Already a feature in the LoL Client) and types out the names of all the champions the player has assigned to that group via a 2nd form. However, if the text is (example) 12345, I've been getting a lot of results like this: 1231234545.
What I've tried:
I've tried adding in ctrl-a + backspace with sendkeys because maybe when it clicks in the search bar it isn't always deleting the stuff there! This however did not change anything
I then commented out the code that types out the actual string (12345) and made the checkbox ONLY type ctrl-a. I then wrote out a string longer than the search bar that I'm typing into and pasted it, clicked a checkbox, and tried to see if it would highlight the text (meaning the text was not always being cleared when clicked). I did this about 50 times and every single time the text was cleared
This leads me to believe that the problem is in the code itself, not the actual integration with the LoL Client. So maybe it's a problem with StringBuilder? I haven't used it very often so I'm not too familiar with it. Commented out all the stringbuilder stuff and changed to String concatenation. Same problem
I tried adding a boolean runningCheckboxFunction to make sure the function would only run once but still have the issue as well.
So this is where I'm at right now. I'm pretty sure it's a problem with my code looping for some reason or the checkbox function as a whole being called twice instead of once when I click the checkbox.
My code:
private void checkboxFunction()
{
if (runningCheckboxFunction == true) return;
runningCheckboxFunction = true;
//CLICK IN THE SEARCH BAR (Automatically clears the text that WAS there)
Process[] LolClient = Process.GetProcessesByName("LolClient"); //should only return one client (i.e. get [0])
if (LolClient.Length < 1) return;
ClickOnPoint(LolClient[0].MainWindowHandle, searchBarCheckPoint);
//MAKE THE STRING TO TYPE IN THE SEARCH BAR
StringBuilder whatToTypeInSearchBar = new StringBuilder();
foreach (CheckBox cb in checkboxes)
{
if (cb.Visible == true && cb.Checked == true)
{
List<String> thisCheckboxsChamps = settingsForm.getChampionListForGroup(checkboxes.IndexOf(cb));
if (thisCheckboxsChamps == null) continue;
foreach (String champ in thisCheckboxsChamps)
{
whatToTypeInSearchBar.Append("|");
whatToTypeInSearchBar.Append(champ);
whatToTypeInSearchBar.Append("$");
}
}
}
//had an issue that sometimes clicking in search bar did not automatically clear it, so select all text and backspace just in case
//^ = ctrl -- ^A = ctrl-A (select all)
SendKeys.Send("^A");
//backspace
SendKeys.Send("{BACKSPACE}");
//TYPE IN THE SEARCH BAR
if (whatToTypeInSearchBar.Length > 0)
{
//remove the first "|"
whatToTypeInSearchBar.Remove(0, 1);
SendKeys.Send(whatToTypeInSearchBar.ToString());
}
runningCheckboxFunction = false;
}
Which event are you using for the check box control (CheckedChanged or CheckStateChanged)? Also, what is the value for CheckBox.ThreeState property? It is possible that the event you use fires more than once. If that is the case, you could check for a specific state before calling the function you have listed above.
Also, when you use SendKeys, try sending the keys to your own application and monitor the ActiveControl.KeyUp/ActiveControl.KeyDown/ActiveControl.KeyPress events to ensure that the string you generate is the riight sequence.
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