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

passing null value to textbox which has decimal number

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

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);//

The best overloaded method match for 'decimal.Parse(string)' has some invalid arguments

你可以这样写你的测试

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");