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

C# 将空值传递给具有十进制数的文本框,c#,visual-studio-2013,sql-server-2008-r2,.net-4.0,C#,Visual Studio 2013,Sql Server 2008 R2,.net 4.0,将空值传递给具有十进制数的文本框 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)”匹配的最佳重载方法有一些 无效参数 您可以用这种方式编写测试 decimal.T

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

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)”匹配的最佳重载方法有一些 无效参数


您可以用这种方式编写测试

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属性从不为null。它可以是一个空字符串,但不能像使用

TB_P.Text = null;
Console.WriteLine(TB_P.Text == null ? "Is null" : "Is not null");

如果文本框包含值0,您想要空值还是仅0?@Steve zero很好我得到了大约10个
textbox
像这样的一个声明十进制变量
result
对于每一个都不是好主意,对吗?例如,有没有解决linq的问题,使它仍然在一行代码中?您不需要声明10个结果变量。你可以重复使用第一个。一旦设置了参数的值,就可以重用相同的变量。此外,在解析用户输入时,确实应该始终使用TryParse方法。如果用户键入的内容不是数字,您会得到一个非常昂贵的例外啊,我现在看到的是Visual Studio-2013。。。。该版本不理解TryParse中结果变量的内联声明。你需要在打电话之前申报。小数结果;十进制.锥巴色(..,out结果);不,空字符串不能解析为十进制。如果对其使用Parse,它将触发异常。您可以在Control.Text的源代码中看到设置TextBox.Text属性时会发生什么。