Quantity button when null crashes windows store app - c#

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

Related

dataGridView get the value of an updated cell when I press enter

I'm a beginner with windows forms and c# in visual studio. Right now, I'm doing a software, where a dataGridView element is used. In there, there is five columns (see Picture), four of them are Read-only and one of them (Column2) can the user modify it (Input Text). The number of rows are defined by the user in an external xml file. Likewise the data in the Columns 1 and 3-5.
When the data is updated in the table, the column 2 is empty and some values should be introduced by the user. The order in which each value is introduced, it is not relevant. However, the value modified in the cell should be saved automatically in a variable in order to be compared later with the values of the column3 and column 4. For example if I give the value 1,2 in the column2 a Message box should be said value between the range otherwise value incorrect.
I was looking the right event where I can save the value into variable when I press enter. I tried making some trials with the following events
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//var selectedcell = dataGridView1.CurrentCell.Value;
//Console.Write(selectedcell);
string msg = String.Format("Row: {0}, Column: {1}",
dataGridView1.CurrentCell.RowIndex,
dataGridView1.CurrentCell.ColumnIndex);
MessageBox.Show(msg, "Current Cell");
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//var item = dataGridView1.Rows[e.RowIndex].Cells[1].Value;
//MessageBox.Show(item.)
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// var row = dataGridView1.Rows[e.RowIndex];
// var changedValue = (string)row.Cells[e.ColumnIndex].Value;
// Console.Write(changedValue);
}
Unfortunatelly, nothing works right now. I don't have any ideas how to implement it.
Try this :
private void dataGridView1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
var column2Value = dataGridView1.GetFocusedRowCellValue(dataGridView1.Columns[1]);
MessageBox.Show(column2Value.ToString())
}
}

C# Input string Error

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

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?

Format error clearing TextBox parsed as integer

I am using Windows Form Application and am having an issue clearing a user textbox. The textbox is getting parsed as an int. I have a button near the bottom of the app that allows a user to clear different parts of the form, labels textboxes etc.
The labels clear fine but any textbox that has been parsed to int I get error on the TextChanged method.
xxx = textbox name
yyy = new int var used in other parts of code
when xxx.Clear(); is called I get exception below:
An unhandled exception of type
System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Here is example of code
private void xxx_TextChanged(object sender, EventArgs e){
// parse user text and convert to int
yyy = int.Parse(xxx.Text);
}
private void btnExit_Click(object sender, EventArgs e){
// close program
this.Close();
}
private void btnClear_Click(object sender, EventArgs e){
xxx.Clear();
}
put the textBoxName.Text in a variable and check if its value is null or not.
int xxx = textbox.Text ;
if(xxx == ""){
//do something
}
well when you use int32.parse you should be carefull that your string be not null and all contain numbers like
"123456789"
if you think you string might be null ot contain not number characters you should use:
int32.TryParse(string String, out int iString);
and use it like this:
int i = 0; // default
string s = "somthing123somthing456blah";
int32.TryParse(s, out i);
result should be: 123456 as integer
EDIT:
if you dont what TextChanged fire:
mytextbox.TextChanged -= myTextBox_TextChanged;
make you change and:
mytextbox.TextChanged += myTextBox_TextChanged;
I suspect something to do with code re-entry. When xxxTxtBox.Clear() is called, the TextChanged method is called, meaning int.parse is called on an empty textbox (null or string.empty can't be parsed to an integer), throwing an exception.
A preferred way to fix that may be setting a flag upon re-entry, something like this.
The easy way is put your TextChanged() logic in a try/catch, meaning that upon re-entry, the int.parse() fails but your user doesn't see a problem.
You need evaluate if the textbox is empty:
enter private void xxx_TextChanged(object sender, EventArgs e)
{
// parse user text and convert to int if value is't Empty
yyy = String.IsNullOrEmpty(xxx.Text) ? 0 : int.Parse(xxx.Text);
}
And try this:
private void btnClear_Click(object sender, EventArgs e){
xxx.Text = String.Empty;
}
To clarify, as some others have pointed out, the problem you are experiencing is due to the fact that xxx_TextChanged() is being called when xxx.Clear() is called and the textbox content changes to an empty string. This causes int.Parse() to execute against an empty string, which produces said error.
To circumvent this problem, you should change the xxx_TextChanged() method to something similar to as follows:
private void xxx_TextChanged(object sender, EventArgs e)
{
// Parse user text and convert to integer, when able:
if ((string.IsNullOrEmpty(xxx.Text)) ||
(!int.TryParse(xxx.Text, out yyy)))
{
yyy = 0;
}
}
Notice the key difference is the "null or empty" check against the text box contents. There is no need to parse a null value or an empty string. Also, instead of using int.Parse(), we can use the int.TryParse() method so that invalid numeric input (e.g., "abc") does not produce an error, but instead is assigned some default value (in this case, 0).
The rest of the code can remain as-is.

C# Conversion throwing exceptions

So, I'm working in C# and for some reason my conversion is throwing exceptions, the code is meant to execute when user presses a button, here is the code.
private void tbVerk6Breidd_KeyDown(object sender, KeyEventArgs e)
{
int width = Convert.ToInt32(tbTextBox.Text); //Crashes here
}
Any help appreciated :)
Edit
Heki mentioned that KeyUp would be a better idea, that worked. Thanks :)
private void tbVerk6Breidd_KeyUp(object sender, KeyEventArgs e)
{
int width = Convert.ToInt32(tbTextBox.Text);
}
if you don't know if the textbox is filled or contains not numerical value, try:
private void tbVerk6Breidd_KeyDown(object sender, KeyEventArgs e)
{
int width;
int.TryParse(tbTextBox.Text, out width )
}
if the text input is not a convertible integer you will retrieve 0
Convert.ToInt32(tbTextBox.Text) can throw two type of exception.
1. FormatException // let say tbTextBox.Text = "abcdefghijkl";
2. OverflowException // let say tbTextBox.Text = "12345890690123456789012345997890";
so check what parameter do you have in tbTextBox.Text.
Solution: As mentioned above use 'TryParse' method of int.
Further read : -https://unwrapdotnet.wordpress.com/2014/01/14/all-about-int32-parse-convert-toint32-int32-tryparse/
The Convert.ToInt32 methods throws two possible exceptions:
FormatException
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException
value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
I guess you get a FormatException because the string within the textbox does not represent a valid int.
In your question you wrote ...the code is meant to execute when user presses a button, here is the code.. But you event handler is registred for a KeyDown event? If you want to check when ever the text within the text box changes (regardless of by copy paste or keyboard interaction) I recommend to use the TextChanged event of the textbox.
private void tbVerk6Breidd_TextChanged(object sender, EventArgs e)
{
int parsed;
if (int.TryParse(tbTextBox.Text, out parsed))
{
// parsed successfully
}
else
{
// invalid value
}
}
try
{
int width = int.Parse( tbTextBox.Text);
// do what you want to do
}
catch
{
// do nothing, log?, display an error message ( that would probably be annoying )
}
You might also want to use a numeric up down control.
https://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(v=vs.110).aspx
I don't know if you want to differentiate between the user actually entering "0", which is a valid input, and the case where they entered invalid data like "abasr4ra".

Categories