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
Related
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.
I want to get result of a value with if condition.
i have get some value in xml file.
now what I want is
if I have a variable "a" here i have assigned some values by using dataset.
and i have another variable "b" is assigned value from xml file.
for example
int a=25;
string b=">10"
now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.
I tried like this but not working
if(a+b)
You can use the DataTable.Compute-"trick" to evaulate such expressions:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
What is supported you can read at the DataColumn.Expression remarks.
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:
b = b.Replace("!=", "<>");
You can have some function to remove non numeric characters:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
If its always a number with a symbol then:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
And considering your comment for comparison you can do:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.
I tried like this
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
similarly all the symbols
First separate symbol from b:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
Now use switch to get operation for symbol and compare:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"
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?
I have read the second line in a text file which contains 2.75 and I am trying to get it to do something if it meets certain criteria. I'm sure I have done this before and has a simple answer but I can't seen to figure it out.
string SecondLine;
using (var reader = new StreamReader(SPFile2))
{
reader.ReadLine();
SecondLine = reader.ReadLine();
}
int NewValue;
NewValue = Convert.ToInt32(SecondLine);
if ((NewValue >= 2) && (NewValue <= 2.99))
{
// Do Something
}
if ((NewValue >= 3) && (NewValue <= 3.99))
{
// Do something else
}
What have I missed out?
You are converting a decimal number to an Int32 that does not hold decimals. This will turn the number in NewValue into 2 as it truncates towards zero. You need to store the variable in a double, float or decimal whichever is best for your requirements.
See the following example that uses a double and Parse:
double newValue = Double.Parse(secondLine);
Note that if you are unsure if the value will be a double you should use Double.TryParse
double newValue;
bool result = Double.TryParse(secondLine, out newValue);
if (!result) //Parse failed
Note that if the parsing fails it may be down to your culture settings i.e. a ',' for the decimal separator not a '.'. However there is an overload for Parse and TryParse that allows you to pass culture information in.
You are trying to parse a string that represents a double into a integer
that will cause a
System.IFormatException
{"Input string was not in a correct
format."}{"Input string was not in a correct format."}
if you know it is a number with decimal part then do:
var newValue = Convert.ToDouble(secondLine);
if you know it is an integer then try:
var newValue = Convert.ToInt32(secondLine);
In my program I have a treeView. In the section that I am working with, the node's displayNames are numerical integer values, but are displayed as strings. I have come to a point in my program where I need to convert and temporarily store these displayNames in an integer variable. I usually use Regex.Match() to do this with no problem, but in this scenario I am getting the compiler error: Cannot implicitly convert type 'string' to 'int'.
This is my code:
//This is the parent node as you may be able to see below
//The children of this node have DisplayNames that are integers
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
for (int i = 0; i < node.Children.Count(); i++)
{
//Error on this line!!**
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
}
}
*NOTE: DisplayName.Value is a string
To get from string to int, use int.Parse(string), it returns the int represented by the passed string and throws if the input format is incorrect.
int.Parse(node.Children.ElementAt(i).DisplayName.Value)
You can also use int.TryParse if you don't want the throw. in that case you would use:
int parsedValue;
if (int.TryParse(node.Children.ElementAt(i).DisplayName.Value, out parsedValue))
{
///Do whatever with the int
}
The problem is becuase you're casting from Match to int in this call
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
Try something like this:
Match m = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
int value = m.Matches[0] //You'll have to verify this line, I'm going from memory here.