程序不会给我正确的总和

时间:2016-05-23 11:00:54

标签: asp.net vb.net

我想获取列表框中所选项目的总和并将其显示在标签中,但我总是得到0,我还想将所选项目放在另一个标签中,这也是无效的。

代码如下所示:

Dim sum As Integer
Dim Items1 As String = "None"

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Label2.Text = Request.QueryString("Name").ToString()

    Dim connetionString As String = Nothing
    Dim connection As SqlConnection
    Dim command As SqlCommand
    Dim adapter As New SqlDataAdapter()
    Dim ds As New DataSet()
    Dim sql As String
    connetionString = "Data Source=.;Initial Catalog=Shop;integrated security=true"
    sql = "select PhoneName,PhonePrice from SmartPhones"
    connection = New SqlConnection(connetionString)

    connection.Open()
    command = New SqlCommand(sql, connection)
    adapter.SelectCommand = command
    adapter.Fill(ds)
    adapter.Dispose()
    command.Dispose()
    connection.Close()
    ListBox1.DataSource = ds.Tables(0)
    ListBox1.DataTextField = "PhoneName"
    ListBox1.DataValueField = "PhonePrice"
    ListBox1.DataBind()


End Sub

显示应该发生的代码:

    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles TotalPrice.Click
   sum = 0 'reset sum to 0
    For Each i As Integer In ListBox1.GetSelectedIndices
        Dim CurrentItem As ListItem = ListBox1.Items(i)
        sum = sum + CInt(CurrentItem.Value)
        Items1 = Items1 + " , " + CStr(CurrentItem.Text)
    Next
    Label3.Text = Items1
    Label1.Text = sum
End Sub

以下是网页设计和网页分别为:enter image description here enter image description here

PhoneName在数据库中的类型为varchar& PhonePrice的类型为整数(两者都正确填充)。

列表框代码:

 <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" ></asp:ListBox>

代码不能给我想要的结果是什么原因?

1 个答案:

答案 0 :(得分:1)

当您点击var target = 2; var tolerance = 0.5; var twoPlusMinusHalf = list.Where(x => Math.Abs(x-target) <= tolerance).ToList(); 执行回发(What is a postback?)时,会发生什么。如果您查看ASP.NET page lifecycle,您会看到TotalPrice事件发生在回发事件处理之前(例如您的Load)。

因此,您单击该按钮,它将运行Me.Load处理程序并且...在单击处理程序有机会运行之前重置您的列表。

有一个属性,您可以检查页面是否因回发而运行:Page.IsPostBack

所以你需要做的就是检查它是否需要填充列表:

Sub Button2_Click