双重不会在ASPX页面上显示

时间:2013-05-10 19:55:53

标签: c# double

我试图在ASPX页面上显示下面的查询(总计)的值,并且我一直得到0.当我输入断点并且调试总数时,所有等于15.0应该是。该值在从中提取的MS SQL数据库中保存为十进制。

.cs Page

public partial class Payment : System.Web.UI.Page
{
    public double total;

    protected void Page_Load(object sender, EventArgs e)
    {
        var id = Request.Params["ID"];
        System.Data.OleDb.OleDbConnection conn;
        System.Data.OleDb.OleDbCommand cmd;
        conn = new System.Data.OleDb.OleDbConnection("--");
        cmd = new System.Data.OleDb.OleDbCommand();
        conn.Open();
        cmd.Connection = conn;
        var sql = String.Format(@"select sum(PayAmt) as total from CurePay where CureID = '{0}'", id);
        cmd.CommandText = sql;
        double total = 0;
        total = Convert.ToDouble(cmd.ExecuteScalar());
        conn.Close();

.ASPX Page

<%= total %>

4 个答案:

答案 0 :(得分:3)

从您的代码中看起来您使用两个单独的变量名称'total',一个是本地的,一个是全局的。正在更新本地的一个,但正在页面上输出全局的一个。

public partial class Payment : System.Web.UI.Page
   {
       public double total; //<< keep this one

       protected void Page_Load(object sender, EventArgs e)
     {
        var id = Request.Params["ID"];
        System.Data.OleDb.OleDbConnection conn;
        System.Data.OleDb.OleDbCommand cmd;
        conn = new System.Data.OleDb.OleDbConnection("--");
        cmd = new System.Data.OleDb.OleDbCommand();
        conn.Open();
        cmd.Connection = conn;
        var sql = String.Format(@"select sum(PayAmt) as total from CurePay where CureID = '{0}'", id);
        cmd.CommandText = sql;
        double total = 0; // << remove the double keyword from this line
        total = Convert.ToDouble(cmd.ExecuteScalar());
        conn.Close();

那应该解决问题......

答案 1 :(得分:1)

更常规的方法可能是在主页上放置一个,然后从Page_Load函数中分配它

<asp:Label ID="lblNumber" runat="server" />


 protected void Page_Load(object sender, EventArgs e)
 {
     // database stuff
     lblNumber.Text = total;
 }

答案 2 :(得分:1)

您引用了两个不同的变量,即全局变量和本地变量。您将本地var设置为0,然后访问全局,只需删除行:

double total = 0;

答案 3 :(得分:0)

尝试使用Label输出您的值

<asp:Label ID="lblValue" runat="server" />

然后将值打印到标签上。

lblValue.Text = Convert.ToDouble(cmd.ExecuteScalar()).ToString();
//this cuts out your variable duplication problem

使用此代替<%= total %>

相关问题