找到文本框为空时,在数据库中插入0

时间:2014-04-29 13:41:18

标签: c# sql sql-server

我有一个Windows窗体应用程序,其中有一些文本框。如果文本框为空,我想在数据库中插入0,否则插入文本框中给出的值。到目前为止,我所做的是分别检查每个文本框。但是我想用一个函数做这个。

我的代码是:

if (other == "")
{
   adp.InsertCommand.Parameters.Add("@otherDeduct", SqlDbType.VarChar).Value = 0;
   otherDeduct = 0.0M;
}
else
{
   adp.InsertCommand.Parameters.Add("@otherDeduct", SqlDbType.VarChar).Value = Convert.ToDecimal(txtOtherDeduct.Text);
   otherDeduct = Convert.ToDecimal(txtOtherDeduct.Text);
}

if (tax == "")
{
   adp.InsertCommand.Parameters.Add("@taxDeduct", SqlDbType.VarChar).Value = 0;
   taxDeduct = 0.0M;
}
else
{
   adp.InsertCommand.Parameters.Add("@taxDeduct", SqlDbType.VarChar).Value = Convert.ToDecimal(txtTaxDeduct.Text);
   taxDeduct = Convert.ToDecimal(txtTaxDeduct.Text);
}

我正在使用SQL Server。

5 个答案:

答案 0 :(得分:0)

创建以下类:

public static class StringExtensions
{
    public static decimal ToTolerantDecimal(this string @this)
    {
       return string.IsNullOrEmpty(@this) ? 0.0m : decimal.Parse(@this);  
    }        
}

现在请致电:

adp.InsertCommand.Parameters.Add("@otherDeduct", SqlDbType.VarChar).Value = 
     txtOtherDeduct.Text.ToTolerantDecimal();

我应该指出,你SqlDbType.VarChar可能有点可疑。

答案 1 :(得分:0)

    foreach (Control in MyForm.Controls)
    {
      if (Control is TextBox)
    {
      string input = null;
      TextBox myTextBox = Control as TextBox;

      if (String.IsNullOrEmpty(myTextBox.Text))
      {
        input = "0";
      }
      else
      {
        input = myTextBox.Text;
      }

     //Never worked with this, maybe you have to edit it for your behaviour.
     adp.InsertCommand.Parameters.Add("@taxDeduct", SqlDbType.VarChar).Value = input;
    }
    }

这样的东西?否则请澄清你的问题。

问候

答案 2 :(得分:0)

你的意思是这样的方法?

private decimal GetValue(string text)
{
    decimal result = 0;

    if (!string.IsNullOrWhiteSpace(text))
    {
        if (decimal.TryParse(text, out result))
        {
            return result;
        }
        else
        {
            throw new Exception("Invalid value");
        }
    }

    return result;
}

答案 3 :(得分:0)

otherDeduct = ParseValue(txtOtherDeduct.Text);
taxDeduct = ParseValue(txtTaxDeduct.Text);

adp.InsertCommand.Parameters.Add("@otherDeduct", SqlDbType.VarChar).Value = otherDeduct;
adp.InsertCommand.Parameters.Add("@taxDeduct", SqlDbType.VarChar).Value = taxDeduct;

public double ParseValue(string value)
{
    return string.isNullOrEmpty(value) ? 0.0M : Convert.ToDecimal(value);
}

答案 4 :(得分:0)

您还可以添加" DEFAULT' 0.0M' "约束到数据库中SQL Server表定义中的相应列。