C# Input string Error - c#

I'm trying too get the users value entered and count down in seconds from it, but whenever I input anything and click the start button it says input string not in correct format. I've googled and googled and cannot figure out how to get the users input and parse or convert it into an int and countdown from it, whilst updating the label via timer of course.
I'm use to console applications still wrapping my head around the syntax...
using System;
using System.Windows.Forms;
namespace Countdown {
public partial class Form1 : Form
{
int seconds; string user; int test = 30;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tmrCountdown_Tick(object sender, EventArgs e)
{
lblDisplay.Text = test.ToString();
if (test > 1)
{
lblDisplay.Text = test.ToString() + " Seconds Remaining";
}
else if (test == 1)
{
lblDisplay.Text = test.ToString() + " Second Remaining";
}
else
{
tmrCountdown.Stop();
}
test--;
}
public void btnStart_Click(object sender, EventArgs e)
{
int test = int.Parse(txtBoxInput.Text);
tmrCountdown.Start();
}
private void txtBoxInput_TextChanged(object sender, EventArgs e)
{
}
}
}
Error is at "int test = int.Parse(txtBoxInput.Text);"

Change Parse into TryParse and see what value can't be parsed:
public void btnStart_Click(object sender, EventArgs e)
{
if (int.TryParse(txtBoxInput.Text, out test))
// We succeed in parsing, so we continue with the timer
tmrCountdown.Start();
else {
// We failed in parsing
// Let's put keyboard focus on the problem text box...
if (txtBoxInput.CanFocus)
txtBoxInput.Focus();
// ... and report what's been happened
MessageBox.Show($"'{txtBoxInput.Text}' is not a valid integer value",
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}

There are two problems in your code.
The first one is the fact that you don't protect your code from invalid inputs. If you don't type something in the txtBoxInput or if you type text that cannot be converted to an integer you get the Invalid String Format Exception
The second problem is the variable test. You declare it locally inside the button click and given the fact that you don't get compilation errors then you are not setting the global class level variable with the same name that you are using in the timer Tick event.
So, use TryParse everytime you need to handle user inputs. This will not raise an exception in case of problems, but just return true or false. Finally do not re-declare the int test variable inside the button click, but use the global class level variable directly in the output of TryParse
public void btnStart_Click(object sender, EventArgs e)
{
// Try to convert the input in an integer. If this succeed you have
// the global variable _test_ set to converted text
if(!Int32.TryParse(txtBoxInput.Text, out test)
MessageBox.Show("Invalid input. Please type a number!");
else
tmrCountdown.Start();
}

try this code at your button
int test=Convert.ToInt32(txtBoxInput.Text);
tmrCountdown.Interval = test*1000; //have to multiply to 1000 since timer interval value is in milliseconds.
tmrCountdown.Start();
Just put integers in your textbox

Related

Validate two textboxes (C #)

I have two textboxes, which prompts the user to enter an integer in each of them. I already have the code all done (code to validate if the texboxes are not empty, if only integers are entered and if the number inserted in the 2nd texbox is greater than the number entered in the 1st texbox.
I leave here a simple example of my code (I already have all the code done):
private async void generate_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
// I already have the code done ...
// error message
}
else
{
// I already have the code done ...
// Here it does the operation with the two numbers entered
}
}
private async void min_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(min.Text, "[^0-9]"))
{
// I already have the code done ...
// error message
}
}
private async void max_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(max.Text, "[^0-9]"))
{
// I already have the code done ...
// error message
}
}
I only have one question: Where do I put the code (I already have this code done) to verify that the number entered in the 2nd textbox is greater than the number entered in the 1st texbox? This is my question.
Update: I just want to know where I put the code:
if (maxValue < minValue)
{
// I already have the code done ...
// error message
}
Encapsulate all of this validation logic in a function the returns a bool
private bool IsValid ()
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
// return false any where the input is not valid
}
}
then use an if statment inside Your Button click Event Handler
if (IsValid())
{
//Code To Check If Max is Bigger Than min
}
this Way You Can Easily Call The IsVaild Function To Check For Empty String
You Can Also Encapsulate The Logic To Validate The Bigger Number in Another function if u gonna use it alot
Hope I Fully Understood You
If your confusion is only where to put the verification code of the number entered in the 2nd textbox is greater than the number entered in the 1st textbox, you can simply check this after the button click. Here's the sample:
private async void generate_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
await new MessageDialog("Text boxes cannot be empty").ShowAsync();
return;
}
if (Convert.ToInt32(max.Text) < Convert.ToInt32(min.Text))
{
await new MessageDialog("1st one is bigger").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
else
{
await new MessageDialog("2nd one is bigger").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
And for your clarification onTextChanged events may be like this:
private async void min_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(min.Text, "[^0-9]") )
{
await new MessageDialog("Enter numbers only.").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
private async void max_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(max.Text, "[^0-9]"))
{
await new MessageDialog("Enter numbers only.").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
So here the summary is, if the textboxes are empty it will show a warning and return. And after the user finishes the input number and presses the button it will check which number is bigger. And a warning will also showed if users give input rather than numbers. Hope this may help you.

System.FormatException occurred in mscorlib.dll when converting it int32

I know, i know there are lots and lots of questions asking on here about this error, each with their own response, but its easier to work off a response regarding your own code rather than someone else's
I have been working on this program for some time for a college assignment, and as soon as i started putting in the class to calculate the totals of things it now crashes,
I don't know where to look so i'll post my main code
enter code here
namespace Till
public partial class MainWindow : Window
{
Calculator calc = new Calculator();
public MainWindow()
{
InitializeComponent();
}
public bool User;
public bool tillopen = false;
private void button_Click(object sender, RoutedEventArgs e)
{
//button clone thingy
Button btn = (Button)sender;
label.Content = label.Content + btn.Content.ToString();
Console.Beep(); // makes the buttons beep
}
private void clear_Click(object sender, RoutedEventArgs e)
{
// Clear
label.Content = "";
}
private void Button_Submit_Click(object sender, RoutedEventArgs e)
{
// submit
listView.Items.Add(label.Content);
label.Content = "";
calc.setSoldItems(Convert.ToInt32(label.Content)); /// it breaks on this line///
}
private void button13_Click(object sender, RoutedEventArgs e)
{
//void sale
label.Content = "";
listView.Items.Clear();
}
private void button15_Click(object sender, RoutedEventArgs e)
{
//pound
label.Content = "1.00";
}
private void button12_Click(object sender, RoutedEventArgs e)
{
//till open close
tillopen = true;
}
private void button16_Click(object sender, RoutedEventArgs e)
{
Login m = new Login();
m.Show();
this.Close();
}
private void button14_Click(object sender, RoutedEventArgs e)
{
label.Content = "2.00"; // 2 pound
}
private void button17_Click(object sender, RoutedEventArgs e)
{
label.Content = calc.finish();
}
}
I have tried to re-create the error in another WPF (converting a to an int32) and it works fine, i know this is an issue with my code itself, i have tried using other machine and using different versions of visual studio itself, so we came to the assumption its this code itself and not a broken dll file
So before I sit down with my Teacher and spend all day going though my code step by step im asking around for help in order to save both of our time, This assignment is due in in 3 weeks, and it decides to break on me now.
thankies
To replicate this error, i press a number button on my Windows form, them hit the submit button i created (which starts the conversion) If a copy of my class which handles all of this is needed im happy to post it
In the method button_click, you have assigned value as
label.Content = label.Content + btn.Content.ToString();
which is a string value to the label and the values are concatenated instead of add.
and when you are reading it, you are converting it in Int32. which will give exception as it will not contain any integer value to it.
You can add the value like this:
label.Content = (Convert.ToInt32(label.Content) + Convert.ToInt32(btn.Content)).ToString();
and check before converting if the label has blank values in it, if it has do not convert them, and only convert the value if it has some values it will not give any error. Also do not assign any values other that numerical digits.
You are calculating:
Convert.ToInt32(label.Content)
but on the line before you set:
label.Content = "";
so this means you are calculating
Convert.ToInt32("")
which gives you a FormatException.
Perhaps you should use the value of label.Content before you overwrite it?

Quantity button when null crashes windows store app

I created a windows store app that has two buttons that will allow my users to select amounts of pictures. The control works when they need to pick the amount but when they click the 'X' inside of the textbox if they want to clear it out and then pressed a button the app crashes.
When I debug I get this error on my block of code:
{"Input string was not in a correct format."}
private void PicturesSubtract_Click(object sender, RoutedEventArgs e)
{
int? value = Convert.ToInt32(this.Pic.Text);
if (value > 1)
{
value--;
}
this.Pic.Text = value.ToString();
}
I get the same error when trying to add or subtract the picture amount.
Any help on this error would be great.
This line throws your error
int? value = Convert.ToInt32(this.Pic.Text);
The reason for this is that Convert.ToInt32 assumes you have a valid integer, and throws an exception in EVERY other case, including null.
http://msdn.microsoft.com/en-us/library/system.convert%28v=vs.110%29.aspx
There are two options I would recommend
The first, null check your text value before doing anything else:
private void PicturesSubtract_Click(object sender, RoutedEventArgs e)
{
if(String.IsNullOrEmpty(this.Pic.Text))
return;
....
The second, use the Int.TryParse method:
private void PicturesSubtract_Click(object sender, RoutedEventArgs e)
{
int value;
if(int.TryParse(this.Pic.Text, out value))
{
//...Do Stuff, Value is stored at this point

Auto refresh labels as text boxes text input data into method

Here is my method that I' am trying to have automatically refresh my label. When I have my label as a click event...the answer refreshes and is correct.
private void Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
}
Here is the Validated label event that does not update when text is changed in my text boxes.
private void lblUtil1_Validated(object sender, EventArgs e)
{
Calculate();
}
If this is correct...what am I missing? is there something I need to do on the text boxes that will trigger validation?
I have also tried a text changed event that yields the error cannot implicitly convert type void(or any type for that matter) to EventHandler. Here is the code.
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged += Calculate();
}
Any help is appreciated! I've been banging my head on my keyboard for a day now.
First at all, you have to handle events for the TextBox that you input value to calculate, such as when you change vale in the TextBox or validate it.
So if you have textBox1 then you should have this handling (trigger when value in textBox1 is changed)
private void textBox1_TextChanged(object sender, EventArgs e)
{
lblUtil1.Text = Calculate();
}
I assume that you want to display value in strUtil1 at the label lblUtil1, so you have to change your Calculate method like this
private string Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
return strUtil1;
}
EDITED
This is a sample code for validate the required TextBoxes.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
lblUtil1.Text = "textBox1 is required!";
}
}
Try calling yourlabelname.Refresh() i.e like
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged = Calculate();
lblUtil1.Refresh();
}
or
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
Calculate();
lblUtil1.Refresh();
}
You need to do a couple things.
First, stop using "hungarian" notation. It's bad. It's bad for a lot of reasons. MS even says, "don't use hungarian" as most people get it wrong as your code shows. Instead, name your variables appropriately. For example, dblSG has absolutely zero meaning.
Second, please reread Michael's answer to your question from yesterday ( https://stackoverflow.com/a/20026642/2424 ). He did NOT say to use lblUtil1_Validated. He said to use TextBox_Validated. In other words, the event you should have your calculation run on is with the textbox fields on your form. He also suggested you just use the textboxes TextChanged events in order to cause the calculation to run as they are typing. Personally, I don't agree with that but whatever.
A third possible option is to simply go back to your original solution. Meaning, just run the calculation when the label is clicked. In which case you should refer back to your original question as Michael failed to answer it.

Opening Image directly into program

I made a basic picture viewer program in C# windows from , following a tutorial.
The program works fine but I want to open it like default windows photo viewer. I tried to open an image with the program directly but that opened the program and the image box was empty.
The image box works fine when images are browsed to open inside the program but how to make it work externally?
Extra : And is there a way to make it full screen?
Sorry for bad english.
P.S: Consider me very noob when helping. Thank you :)
namespace Basic_Picture_Viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void showButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
}
private void backgroundButton_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.BackColor = colorDialog1.Color;
}
}
private void closeButton_Click(object sender, EventArgs e)
{
ActiveForm.Close();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
else
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void rotateButton_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
Image img = pictureBox1.Image;
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Image = img;
}
}
}
Okay, so in your Program.cs file, implement the commmand line arguments according to the link in the comment above, and pass it to the form.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if(args.Length > 0)
Application.Run(new Form1(args[0]));
else
Application.Run(new Form1());
}
Then in your form, change the constructor to
public Form1(String fileName = null)
{
InitializeComponent();
if (fileName != null)
{
// Add validation to ensure file exists here
this.WindowState = FormWindowState.Maximized;
pictureBox1.Load(fileName);
}
}
You'll either want a try/catch block or something to check for the existence of the file before attempting to open it. Under the use case you describe I would consider a missing file an exceptional case, so that seems like a plan to me.
The statement public Form1(String fileName = null) specifies one optional argument.Optional arguments are arguments that have a default value in the function,you always have the option to either call the function with or without argument,if you specify any argument the new argument is used in place of default argument,and in case you don't specify an argument when calling the function the default argument is used.The default value to optinal argument must always be a value that is a constant at compile time.To better clarify that let me take an example.Consider we have a function that adds two numbers.
private int AddNumbers(int a=10,int b=15)
{
int c=a+b;
return c;
}
We have specifies two optional arguments for the function,the above functions doesn't flag any error but as I said optional arguments must have a default value which is know at design time so the function below flags an error that follows Default parameter values must be compile time constant. because it uses default values that will be known at runtime.
int z,x;
private int AddNumbers(int a=z,int b=x)
{
int c=a+b;
return c;
}
Consider that the variables z and x are calculated using some logic at runtime,but are not unknown at compile time.This would flag the error.
Next,let me tell you differences in a normal function and a functional with optional parameters.The first function that compiles with no errors can be called in two ways;
**By passing some arguments when calling**
AddNumbers(5,15);
This will return 20.
**By calling the function without specifying any arguments**
AddNumbers();
This will return 25,remember we defined 10,15 as default arguments.Both the calls are valid and will compile without any errors.
So now I hope you've found answer to your question,if you would like to read more have a look here.

Categories