-3

Im using the Mahapps.Metro framework for my C#, Wpf Application. In the framework is the wpf element: NumericUpDown.

Now I used the element like this:

<Controls:NumericUpDown Name="numCreateArticleStock" Minimum="0"/>

Now I want to convert the entered value in the field into a int value.

Here is my try:

int articleStock = 0;

if(!Int32.TryParse(numCreateArticleStock.Value, out articleStock)
{
    await this.ShowMessageAsync("Error", "Error - Message");
}

I get this error:

  1. Cannot convert "double?" in "string"

Maybe someone of you have an Idea, Thanks!

Name
  • 564
  • 1
  • 8
  • 18

2 Answers2

5

The error you get is because the TryParse method expects as string value, but you have a double? value.

There is no need to parse the value, you can just convert it from double:

int articleStock = (int)numCreateArticleStock.Value.GetValueOrDefault();

The GetValueOrDefault method will turn a null value into 0, I assume that's what you want when there is no value to get from the control.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Since numCreateArticleStock.Value is a double? why not just check if it is null and then cast it to int if it is not null.

int articleStock = 0;
if(!numCreateArticleStock.Value.HasValue)
{
    // value is null decide what to do in that case.
}
else
{
    articleStock = (int)numCreateArticleStock.Value.Value;
}
juharr
  • 31,741
  • 4
  • 58
  • 93