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

本文关键字:数据库 提取 | 更新日期: 2023-09-27 18:30:41

我有一个包含几个不同游戏的下拉列表,我需要从下拉列表中选择项目,在同一个数据库中查找数量,然后将它们相乘并在价格文本框中打印总数,我如何让它工作? 我的 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();
    }
}

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

不应

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

TextBox2.Text = sum;

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