添加两个标签值,然后将结果插入表中

时间:2014-04-07 19:20:16

标签: asp.net sql

我想添加两个存储在两个标签中的值(主要是十进制值),然后使用sqlcommmand将其插入到表中。这是我的代码:

      protected void Button1_Click(object sender, EventArgs e)
{
    double balance;
    double reward;
    Session["FinalBalance"] = (double.TryParse(lblBalance.Text, out balance) + (double.TryParse(lblReward.Text, out reward)).ToString());
    lblFinal.Text = Session["FinalBalance"].ToString();
    string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Insert into tblRegister('Balance') values('@FinalBalance')", con);
        cmd.Parameters.AddWithValue("@FinalBalance", Session["FinalBalance"].ToString());
    }


}

现在发生的事情是,它没有将总和插入表中。所以我通过将其值传递给标签来检查总和,并且它给出了“TrueTrue”。我猜它是在给出布尔结果我怎么去了?

2 个答案:

答案 0 :(得分:0)

你应首先使用double.TryParse检查double值,然后如果为true则为double,如果不是,则将值设置为0.

以下内容应该有效:

protected void Button1_Click(object sender, EventArgs e)
{
          double balance;
          bool isDouble = double.TryParse(lblBalance.Text, out balance);
          if(!isDouble)
          {
              balance = 0;
          }

          double reward;
          bool isDouble2 = double.TryParse(lblReward.Text, out reward);
          if(!isDouble2)
          {
              reward=0;
          }

          Session["FinalBalance"] = balance + reward;

          lblFinal.Text = Session["FinalBalance"].ToString();
          string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
          using (SqlConnection con = new SqlConnection(CS))
          {
              con.Open();
              SqlCommand cmd = new SqlCommand("Insert into tblRegister('Balance') values('@FinalBalance')", con);
              cmd.Parameters.AddWithValue("@FinalBalance", Session["FinalBalance"].ToString());
          }
}

答案 1 :(得分:0)

double.TryParse返回一个布尔值。 '解析'价值在你的余额和奖励输出变量中。

你会想要这样的东西:

if((double.TryParse(lblBalance.Text, out balance) && (double.TryParse(lblReward.Text, out reward))){
    Session["FinalBalance"] = balance + reward;
}
else{
    // some kind of error handling
}