开发者

Convert ComboBox to Decimal, C#

I am trying to create a combobox that contains text and when each text is chosen the text will equal a decimal and later be used in a math code. I am using C# inside Visual Studio.

I am a beginner and any help 开发者_开发问答will be greatly appreciated.

Thanks, Royal


That should be reasonably simple. You can use Decimal.Parse() to convert the selected string value to a decimal:

decimal val = Decimal.Parse(someComboBox.SelectedItem.ToString());


If you know that the string is definately a Decimal you can use Justin's answer, if you are unsure if it is a Decimal you could also try:

decimal ParseDecimal(string str){
decimal number;

    if(Decimal.TryParse(str, out number)
    {

         return number;
    }
    return decimal.MinValue (or any other value that you know to check against)
}

Where the string you pass into the method is the combo box string.


Are you looking to convert the input string to decimal? This may help. http://msdn.microsoft.com/en-us/library/59095yyw.aspx and also Decimal.TryParse http://msdn.microsoft.com/en-us/library/9zbda557.aspx


or if you are sure you can use Convert method:

decimal val = Convert.ToDecimal(comboBox1.SelectedItem.ToString());

But becuase you said you are unsure about what string value is (or is a decimal, or a dobule, or a simple stirng, or ...) it would be better to use Darren`s version of checking, which will check if the string is a actual decimal value. If it is, it will go into the brackets (and you can do something then), if its not, then it will go over if statement (you can add an else statement to do something else.

Mitja

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜