Textbox to Label errors in C# - c#

I am building a WinForm in C# and have no clue what I am doing. I have made it this far and this section is working but after entering numbers into the textbox and then removing them to change them I get an "Input string was not correct format" error. I am pretty sure this is because it is returning to a blank state and have tried putting an If statement in but keep getting errors on that because of Int or String type. How can I handle this and I am sure this is not the easiest or best way to do it but its how I got this working so far.
Thanks,
private void txt_RP7_TextChanged(object sender, EventArgs e)
{
int rw = Convert.ToInt32(txt_WeightRemain.Text);
int ld = Convert.ToInt32(txt_LayerD.Text);
int pl = rw * ld / 100;
int rp = Convert.ToInt32(txt_RP7.Text);
int rwr = pl * rp / 100;
string rwrs = rwr.ToString();
lbl_RW7.Text = rwrs ;
}

Use TryParse when dealing with input from users that may be invalid entries.
if (int.TryParse(txt_WeightRemain.Text, out var rw))
{
// valid int
}
else
{
// does not represent an int
}

Try to not use Convert. Try using
int.TryParse(txt_WeightRemain.text, out int rw)
int _rw = rw
Why? Because with that, if the text box is empty it will give you 0 for the value, not null or empty string.
When using convert and the value is empty then it will give such an error.
And try to make your code more safe to avoid the divison by zero error. Basic math for that.
Sorry for my bad english, just trying to help.

Related

how to convert a String list into a String array then converting it into an int array then counting the total sum of the numbers in the array?

So I am so fresh into the world of programming, starting new, I decided to start messing around in C# to create simple apps from ideas that come to mind, with this little app, I'm trying to have multiple TextBoxes named d1,d2,d3,d4,etc... the user inserts numbers into the textboxes then clicks button1, which begins the process in the code below creating a new list which contains all of the values of the textboxes and then the list is converted to an array and the array is then converted into an int array, etc....
BUT, when starting the application and I add values to the textboxes and then click button1, it shows 2 error like shows in the //gray code line below
Please help.
private void button1_Click(object sender, EventArgs e)
{
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
foreach(string numb in dodo)
{
if (numb == "")
numb = "0"; //numb word has a red underline
}
string[] terms = dodo.ToArray();
int[] valv = {};
int x = 0;
for(int i=0;i<=19;i++)
{
valv[i] = int.Parse(terms[i]); //the ; in the end has a red underline and shows "FormatException was unhandled" error
i++;
x = x + valv[i];
}
string myString;
myString = x.ToString();
Result1.Text = myString;
}
you can't change the iteration variable which is numb in your case. Please change in the List container instead
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
int k = 0;
foreach (string numb in dodo)
{
if (numb == "")
{
//numb = "0"; //numb word has a red underline
dodo[k] = "0";
}
k++;
}
Now your code on parsing into integer won't give any runtime error.
The first line "tells" you that you are not able to assign a new value to the variable which is used as a foreach iteration variable.
The second line, "tells" you that you have string value which is not able to be parsed correctly (e.g. user put string which is not a number). To avoid this you can use Int32.TryParse method instead, which will safely try to parse the given string.
The best and easiest way to achieve what you need is using LINQ methods, here is the example based on few things/assumptions:
Since you are converting empty strings into zeros, you could simply skip those entries from counting
To avoid FormatException, you should use TryParse method instead. Since TryParse method will safely parse the given string, you don't even have to filter empty strings at all (they will be skipped). However, I deliberately left filtering part, to get you a better overview of a solution.
You can use list initializer to make list initialization more readable
Solution:
List<string> dodo = new List<string>()
{
d1.Text, d2.Text //...others
};
int sum = dodo
.Where(item => !String.IsNullOrEmpty(item))
.Sum(item =>
{
if (Int32.TryParse(item, out int parsedItem))
{
return parsedItem;
}
return 0;
});
You can get more familiar with LINQ and used methods on following link

Form crashes when opening

Whenever I open my form (the one which stuff is being sent to) it crashes because a of a certain part. The part that is breaking it is Convert.ToInt32(txt_cost). Im looking to know how this should be sent to my other form without crashing the program
private void btn_HomepageSearch_Click(object sender, EventArgs e)
{
if (isValidData())
{
string destination = cbo_Destination.Text;
DateTime checkIn = date_FlightDate.Value;
frm_BookingPg frm_HomePge = new frm_BookingPg(cbo_Destination.Text, cbo_AmountOfPeople.Text, Convert.ToInt32(txt_cost));
frm_HomePge.Show();
this.Hide();
}
}
Assuming you have an integer in your text box, i believe that should be
Convert.ToInt32(txt_cost.Text)
if it still crashes then the value of txt_cost can't be a valid int. try the below
var intValue = 0;
if (int.TryParse(txt_cost.Text, out intValue))
{
//do something with intValue
}
EDITED
( Code part from the comment of #Minimarshman ) :
case "ten":
price1 = 10;
break;
decimal total = price * price1;
txt_cost.Text = total.ToString("c");
So as you can see you're converting decimal to string and then assign that into a TextBox's Text property.
ALWAYS leave some margin for errors especially when you're doing software development. Meaning that you should NEVER TRUST that user will use your software as it was intended. Your usage of Convert.ToInt32(txt_cost) shows that you trust your/user data too much.
To deal with this you have to check every data that you're converting if it really is a valid data. c# has many built-in methods/functions that will validate that and the one you should use is decimal.TryParse which ensures that data is valid for the type conversion.
Another thing is that you're using special format for your ToString ("C") which indicates that it should put currency mark in the string. You have to remember to then get rid of this.
Code explanation :
decimal IfValueIsConvertibleItWillBeHeldHere = 0;
if(decimal.TryParse(txt_cost.Text.Split(' ')[0], out IfValueIsConvertibleItWillBeHeldHere)
{
frm_BookingPg frm_HomePge = new frm_BookingPg(
cbo_Destination.Text,
cbo_AmountOfPeople.Text,
(int)IfValueIsConvertibleItWillBeHeldHere // see the difference ?
);
frm_HomePge.Show();
this.Hide();
}
else
{
// show some message to the user that input was invalid
}
Remarks :
Doing so leaves you with chaotic code because converting from decimal to int using explicit type conversion will trim that value. For example decimal d = 0.5M; explicitly converted to int like int i = (int)d; will return 0 because it trims down the part after decimal mark ..
You should rewrite your frm_BookingPg to accept decimal type instead of int type so that the value will be accurate :
public frm_BookingPg(string destination, string amountOfPeople, decimal cost)
Instead of your actual :
public frm_BookingPg(string destination, string amountOfPeople, int cost)
Have you tried replacing
Convert.ToInt32(txt_cost)
with just an int32 literal value?
As follows:-
frm_BookingPg frm_HomePge = new frm_BookingPg(cbo_Destination.Text, cbo_AmountOfPeople.Text, 1234);
does it still crash?

Why do I get "Invalid args" at runtime with this code?

I've got this code to conditionally format a cell after it has been assigned to, based on the value it contains:
var avgWeeklyDeliveriesCell = (Excel.Range)_xlSheet.Cells[curDelPerfRow,
AVG_WEEKLY_DELIVERIES_COLUMN];
avgWeeklyDeliveriesCell.Value2 = string.Format("=ROUND(AVERAGE(C{0}:I{0}),
2)", curDelPerfRow);
avgWeeklyDeliveriesCell.NumberFormat = "#,##0.00";
ConditionallyHighlight(avgWeeklyDeliveriesCell.Value2,
_xlSheet.UsedRange.Row);
private void ConditionallyHighlight(string cellVal, int rowIndex)
{
int COL_K_INDEX = 11;
float avgWeeklyDelivery = float.Parse(cellVal,
CultureInfo.InvariantCulture);
if (avgWeeklyDelivery > delsPerWeek)
{
Excel.Range cellToHighlight = (Excel.Range)_xlSheet.Cells[rowIndex
COL_K_INDEX];
cellToHighlight.Interior.Color = OUT_OF_BOUNDS_HIGHLIGHT_COLOR;
}
}
The problem is with cellVal; it seems to be a string, as I'm assigning the results of a String.Format() call to the cells' Value2 property, and then passing that (value2) to the method that is to conditionally format the cell.
It compiles, but at runtime it fails with an "invalid args" message. Why, and how can I fix it?
After you setup the formula to Value2, this property will returns the evaluated value, which is a int/double in this case. So you will not need to parse the value.
Just change the parameter cellVal type to double:
private void ConditionallyHighlight(double cellVal, int rowIndex)
{
int COL_K_INDEX = 11;
if (cellVal > delsPerWeek)
{
Excel.Range cellToHighlight = (Excel.Range)_xlSheet.Cells[rowIndex,
COL_K_INDEX];
cellToHighlight.Interior.Color = OUT_OF_BOUNDS_HIGHLIGHT_COLOR;
}
}
In this line you are passing in a Value2
ConditionallyHighlight(avgWeeklyDeliveriesCell.Value2, _xlSheet.UsedRange.Row);
But the Value2 is a Range-object in Excel and - maybe - not directly useable in C#.
Have a look to D Stanley's comment (Thx!) who cleard this point.
Here is a somehow related question: Casting Range.Value2 of Excel interop to string
Try to add a ".ToString()" after Value2 and be aware of the possibilities of "null". Better use float.TryParse()
string YourString = "ImpossibleValue";
float f;
if (!float.TryParse(YourString, out f)) {
//React on the failed parsing (default value, error...
}
//go ahead with f, which holds the correct (or defaulted) value
Here's some background: https://msdn.microsoft.com/en-us/library/office/ff193553.aspx

converting int var to string var with unassigned local variable error

I am trying to convert an int var to a string var for use in a .txt file. i am coming up with a "unassigned local variable error". I have looked thru other questions but i don't see what i am missing. I have been able to convert int var to a string var before, i am not really sure where i am going wrong. If you could also give me the theory with the solution it would be most helpfull
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
if (BTSBtn.Checked)
{
sbntmsk = 30;
}
string subntmsk;
subntmsk = sbntmsk.ToString();
The compiler has no way to know if your checkboxes will be checked at runtime and so it complains because there is a possibility that the variable sbntmsk reaches the point where you try to convert it to a string without having a value assigned.
To fix the message declare and initialize sbntmsk with (or whatever default value you like)
int sbntmsk = 0;
You need to provide a default value for the integer. For example, what would you expect to be in the string if neither button was checked?
You could just use strings?
var sbntmsk = String.Empty;
if (RBSBtn.Checked)
{
sbntmsk = "29";
}
if (BTSBtn.Checked)
{
sbntmsk = "30";
}
Try using this approach:
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
else if (BTSBtn.Checked) // Notice the ELSE - IF
{
sbntmsk = 30;
}
else
{
sbntmsk = 0; // a default value
}
string subntmsk = String.Empty; // initialize with empty
subntmsk = sbntmsk.ToString();
Since using multiple checkboxes you are assigning to a same variable so no need to check all IF blocks. Also, using this way you have a possibility to define an 'ELSE' block at the end.
Hope it helps!

conversion from string to int while passing as a parameter in a method

I have a method that inputs an integer as a parameter in a class -
public string OddNumbers(int input)
and in my main program, I am trying to accept an integer from the user, through a textbox, and I am converting the input string to integer while passing the parameter -
string odd = od.OddNumbers(int.Parse((TextBox1.Text))).ToString();
and I am getting the following error:
"System.FormatException: Input string was not in a correct format."
I tried different methods of converting the integer to string, but results in the same error, for example:
string odd = od.OddNumbers(Convert.ToInt32(TextBox1.Text));
Any help in pointing out where I am going wrong?
What input are you trying to enter?
I would try a couple of things.
1) Run a trim on the input before passing it into the parse command. This will make sure there are no empty spaces at the end of the number.
2) If you are trying to accept a decimal, make sure you use double.
Do not nest functions, it makes code incredibly difficult do debug and maintain.
int Number;
if (int.TryParse(TextBox1.Text, out Number) == false)
{
// parsing error
Number = -1;
}
string odd = od.OddNumbers(Number);
The following should work assuming that the user enters a valid integer in the textbox:
int i = int.Parse(TextBox1.Text);
string odd = od.OddNumbers(i).ToString();
Another possible way to handle this is to use the TryParse method:
int i;
if (int.TryParse(TextBox1.Text, out i))
{
string odd = od.OddNumbers(i).ToString();
}
else
{
MessageBox.Show(TextBox1.Text + " is not a valid integer");
}
Once i put the method inside an click event, which finds out whether the input integer is odd or even, it gave me the desired result. thanks for all the inputs.

Categories

Resources