是否有另一种方法可以在不使用 Convert 的情况下转换用户在条目中输入的值?....(Convert.ToDouble 或 Convert.ToInt)
Is there another way of converting a value entered by a user in an entry without using Convert?.... (Convert.ToDouble or Convert.ToInt)
我正在使用 syncfusion 数字文本框,因为我希望用户在文本框中输入双精度值。但是,当我使用 ConvertToDouble 或 ToInt 时,如果它为 null,则它 returns 值为 0。是否有任何选项可用于转换?
//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
};
您可以使用方法 String.IsNullOrEmpty()
来检查值并使用 try- catch
来实现。
例如,您可以这样做:
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...");
}
注:
- 您可以使用方法
String.IsNullOrWhiteSpace
过滤输入数据。
之后,您可以使用方法 value.Trim().Length == 0
来验证它是否是 whitespaces
.
- 您可以根据需要调整代码。
我正在使用 syncfusion 数字文本框,因为我希望用户在文本框中输入双精度值。但是,当我使用 ConvertToDouble 或 ToInt 时,如果它为 null,则它 returns 值为 0。是否有任何选项可用于转换?
//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
};
您可以使用方法 String.IsNullOrEmpty()
来检查值并使用 try- catch
来实现。
例如,您可以这样做:
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...");
}
注:
- 您可以使用方法
String.IsNullOrWhiteSpace
过滤输入数据。 之后,您可以使用方法value.Trim().Length == 0
来验证它是否是whitespaces
. - 您可以根据需要调整代码。