【问题标题】:passing null value to textbox which has decimal number将空值传递给具有十进制数的文本框
【发布时间】:2018-10-12 18:57:41
【问题描述】:

将空值传递给具有十进制数字的文本框

cmd.Parameters.Add(new SqlParameter("@P", SqlDbType.Decimal)).Value = decimal.Parse(TB_P.Text == null ? DBNull.Value : (object)TB_P.Text);//decimal.Parse(TB_P.Text);//

'decimal.Parse(string)' 的最佳重载方法匹配有一些 无效参数

【问题讨论】:

  • 如果文本框包含值 0,你想要一个 null 还是只需要 0?
  • @Steve zero 也不错

标签: c# visual-studio-2013 sql-server-2008-r2 .net-4.0


【解决方案1】:

你可以这样写你的测试

decimal.TryParse(TB_P.Text, out decimal result);
cmd.Parameters.Add("@P", SqlDbType.Decimal).Value = (result == 0 ? (object)DBNull.Value : result);

但如果 0 是要写入的有效值,那么您需要更详细

object value;
if (!decimal.TryParse(TB_P.Text, out decimal result))
    value = DBNull.Value;
else
    value = result;

cmd.Parameters.Add("@P", SqlDbType.Decimal).Value = value;

另请注意,TextBox.Text 属性永远不会为空。它可能是一个空字符串,但不是一个空值,因为

很容易证明
TB_P.Text = null;
Console.WriteLine(TB_P.Text == null ? "Is null" : "Is not null");

【讨论】:

  • 我有大约 10 个 textbox 像这样一个声明十进制变量 result 的每个不是好主意,对吗?例如使用 linq 的任何解决方法,所以它仍然在一行代码中?
  • 您不需要声明 10 个结果变量。您可以重复使用第一个。设置参数的值后,您可以重复使用相同的变量。
  • 另外,在解析用户输入时,您确实应该始终使用 TryParse 方法。如果用户输入的不是数字,你会得到一个非常昂贵的异常
  • 啊,我现在看到 Visual-Studio-2013.... 该版本不理解 TryParse 中结果变量的内联声明。您需要在调用之前声明它。 十进制结果; decimal.TryParse(...., out result);
  • 没有空字符串不能解析为小数。如果您在其上使用 Parse,它将触发异常。您可以在 Control.Text 的源代码中看到 referencesource.microsoft.com/#System.Windows.Forms/winforms/… 在您设置 TextBox.Text 属性时会发生什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多