String value not passing correctly

98 Views Asked by At

In my program I have a TreeViewItem with it's Header set to a numerical integer value. In order to convert the Header to a straight int value I pass to a function called getNumber.

My getNumber function:

This function comes from this previously asked question.

//Gets the number contained in a Node's header
public static int getNumber(string parentNodeHeader)
{
    int curNumber = 0;
    Int32.TryParse(parentNodeHeader, out curNumber);
    return curNumber;
}

I pass to this function the same way in a few different areas in my program, but in one of them the string doesn't pass correctly. In the debugger it (parentNodeHeader) displays "System.Windows.Controls.StackPanel" as it's value instead of a number. I have no idea why this is happening.

For the working calls to the function, as well as the not working call I use the same code.

int curNumber = getNumber(SelectedItem.Header.ToString());

Why would this be happening and how can I fix it?

UPDATE:

I've changed my call to the getNumber function by adding this...

var selectedHeader = (TextBlock)SelectedItem.Header; //The header is now a TextBlock
int curNumber = getNumber(selectedHeader.Text);

Theoretically this should work, but I am getting an InvalidCastException that says it could not cast StackPanel to TextBlock. Where is StackPanel coming from...?

Thanks for your help.

1

There are 1 best solutions below

0
On

Instead of using the getNumber() function I used Regex to extract the integer from the string.

In order to use Regex you need to include System.Text.RegularExpressions;

Then you implement it like so: var data = Regex.Match(stringValue, @"\d+").Value;