Search code examples
c#windows-8textboxwindows-store-appswindows-store

Convert textbox value to another data type in Windows Store with C#


Sorry for this question. I just got confused by the code to convert or parse value from textbox to int, float, double, etc in windows store. I'm a C# user and I tried this code

block1 = Convert.ToDouble(text1.Text); or block1 = double.Parse(text1.Text);

those method didn't work for me, does anybody can help me out? Thank you.


Solution

  • If you want to be able to easily select what type you want to covert the string to (int, double, float) you could make a simple method to convert the string.

    Something like

    private T ConvertTo<T>(string value) where T : IConvertible
    {
        try
        {
          return (T)Convert.ChangeType(value, typeof(T));
        }
        catch (Exception)
        {
        }
        return default(T);
    }
    

    Usage:

    string value = "33";
    
    int intVal = ConvertTo<int>(value);
    float floatVal = ConvertTo<float>(value);
    double doubleVal = ConvertTo<double>(value);