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
The problem is becuase you're casting from
Match
toint
in this callIntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, @"\d+").Value;
Try something like this:
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.
You can also use int.TryParse if you don't want the throw. in that case you would use: