tags:

views:

617

answers:

2

Hi all, i have a NumericUpDown control and want to update its contents from the registry. So far this is what i got:

this.apTime.Value = APRegsitry.GetValue("apTime").ToString();

Obviously that wont work so how do i set this.apTime to the value of the registry key?

+1  A: 

I'm not entirely sure what the issue is. Are you having problems converting it to a decimal? If so try Decimal.Parse

Object obj = APRegistry.GetValue("apTime");
String str = obj != null ? obj.ToString() : "0";
Decimal value = Decimal.Parse(str);
this.apTime.Value = value;

If not can you elaborate further as to what the problem is?

EDIT Updated code to account for null return from GetValue

JaredPar
Decimal value = Decimal.Parse(APRegistry.GetValue("apTime").ToString());You forgot to add the Decimal.Parse. :)Also you can try Convert.ToDecimal(stringValue);
Chris Brandsma
@Chris, It's embarassing to forget the line your entire answer is based around. Thanks!
JaredPar
i keep getting "An unhandled exception of type 'System.NullReferenceException' occurred in program.exe" with both decimal.parse and convert.todecimal
wait.. o keep getting that because the key didnt exist :S it works now thanks :D
@Tony updated the code to work with a non-existent value
JaredPar
thanks alot. works perfectly
One more syntax error... no parens after ToString.
Daniel Earwicker
+1  A: 

You shouldn't trust the value from the registry since a user can edit it outside your application. You need to handle the following cases:

  • registry key doesn't exist
  • registry key exists, but name/value doesn't exist (null)
  • you expect a string, value is not string type (e.g. it is an int or byte[])
  • value is a string but not parsable to decimal ("", "abc")

If the key doesn't exist, RegistryKey.OpenSubKey(name) returns null. You might want to handle that and create the key. If the key exists, but not the name/value pair, then RegistryKey.GetValue(name) returns null. You can handle that by passing a default value to the overload RegistryKey.GetValue(name, defaultValue) or by using ??.

Now, if the name/value pair exists but has an invalid value ("", "abc"), you'll get an exception from Parse(). The Parse() methods (in int, decimal, DateTime, etc) have been pretty much been deprecated by TryParse(). They return false instead of throwing FormatException.

// passing the default value to GetValue()
object regValue = APRegistry.GetValue("apTime", "0");
// ...same as...
object regValue = APRegistry.GetValue("apTime") ?? "0";

decimal value;

// regValue will never be null here, so safe to use ToString()
if(decimal.TryParse(regValue.ToString(), out value))
{
 this.apTime.Value = value;
}
else
{
 // Name/pair does not exist, is empty,
 // or has invalid value (can't parse as decimal).

 // Handle this case, possibly setting a default value like this:
 this.apTime.Value = 0; 
}
Lucas