如何从数据库中提取数量并将其乘以得到总数

时间:2014-11-16 18:09:57

标签: c# asp.net visual-studio-2012

我有一个包含几个不同游戏的下拉列表,我需要从下拉列表中选择项目,在同一个数据库中查找数量,然后将它们相乘并在价格文本框中打印总数,如何做我让这个工作?我的HTML是......

<asp:DropDownList ID="ddlProducts" GroupName="Contact" runat="server" DataSourceID="SqlDataSource1"
                DataTextField="Name" DataValueField="Name" Width="198px" AppendDataBoundItems="True">
            </asp:DropDownList>

    &nbsp &nbsp<asp:Label ID="Label3" runat="server" Text="Quantity:" 
        Width="80px" BorderWidth = "0px"></asp:Label>
      <asp:TextBox ID="txtQuantity" runat="server" Width="80px"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ControlToValidate="txtQuantity" Display="Dynamic"
        ErrorMessage="Quantity is a required field.">
    </asp:RequiredFieldValidator>
    <asp:RangeValidator ID="RangeValidator1" runat="server"
        ControlToValidate="txtQuantity" Display="Dynamic"
        ErrorMessage="Quantity must range from 1 to 10." 
        MaximumValue="500" MinimumValue="1" Type="Integer">
    </asp:RangeValidator><br /><br />

    <asp:Label ID="Label4" runat="server" Text="Total:" 
        Width="80px" BorderWidth = "0px"></asp:Label>
     <asp:TextBox ID="TextBox2" runat="server" Width="80px" OnTextChanged="TextBox2_TextChanged"></asp:TextBox><br />

这是我背后的代码......

 protected void TextBox2_TextChanged(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from price where" +
        ddlProducts.SelectedValue + "'", con);
        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();

        if (txtQuantity.Text.Length > 0 && txtQuantity.Text.Length > 0)
        {

        float price = Convert.ToInt32(txtQuantity.Text);
        int quantity = Convert.ToInt32(txtQuantity.Text);

        float sum = price * quantity;
        return sum;

        strCon = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        con = new SqlConnection(ConnectionString);
        con.Open();

    }
}

1 个答案:

答案 0 :(得分:0)

你不应该在TextBox2_TextChanged方法中调用return,而是将值设置为HTML控件:

TextBox2.Text = sum;

另请注意,当您在文本框中按Enter时会触发TextBox2_TextChanged,但您可能不想要此事件...我想您要将所有代码从TextBox2_TextChanged内移动到新的DropDownList_ddlProducts更改事件中。