Search code examples
xamarinsyncfusion

Is there another way of converting a value entered by a user in an entry without using Convert?.... (Convert.ToDouble or Convert.ToInt)


I am using syncfusion numeric textbox because I want the user to enter double value into the textbox. But when i use the ConvertToDouble or ToInt if it's null then it returns a value of 0. Is there any option I can use for conversion?

//from database
    public double rain1vol { get; set; }
    [MaxLength(3)]
    public double rain2vol { get; set; }

//user entered to database
Post post = new Post()
        {
          rain1vol = Convert.ToDouble(Sfrain1Entry.Value),
          rain2vol = Convert.ToDouble(Sfrain2Entry.Value),

       rain2vol = Sfrain2Entry.Value == null ? null : Convert.ToDouble(Sfrain2Entry.Value); 
//this is the line i've tried but has error
// no implicit conversion between null and int.

            // rain1vol = rain1Entry.Text,
            //rain2vol = rain2Entry.Text

        };

Solution

  • You can use method String.IsNullOrEmpty() to check the value and try- catch to achieve this .

    For example, you can do like this:

           var value = Sfrain1Entry.Text;
    
            if (!String.IsNullOrWhiteSpace(value))
            {
                double result1;
                try
                {
                    result1 = Convert.ToDouble(value);
                    System.Diagnostics.Debug.WriteLine("The input is : " + result1);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
                }
            }
            else if (value.Trim().Length == 0)
            {
                System.Diagnostics.Debug.WriteLine("The input is IsWhiteSpace...");
            }
            else {
                System.Diagnostics.Debug.WriteLine("The input is invalid...");
            }
    

    Note:

    1. You can use method String.IsNullOrWhiteSpace to filter the input data. After that , you can use method value.Trim().Length == 0 to verify if it is whitespaces.
    2. You can adjust the code according your requirement.