2014-01-16 18 views
1

我試過以下代碼將哈希表與列表框綁定在一起。在asp.net中雙擊時間的HashTable輸出

的.aspx:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Hashtable.aspx.vb" Inherits="Hashtable" %> 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head id="Head1" runat="server"> 
     <title>Untitled Page</title> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
     <div> 
      <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> 
      <br /> 
      <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox><br /> 
     </div> 
     </form> 
    </body> 
    </html> 

.aspx.vb

#Region "Namespaces" 

    Imports System.Data 
    Imports System.IO 
    Imports System.Net.Mail 

    #End Region 
    Partial Class Hashtable 
     Inherits System.Web.UI.Page 

     Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 
      Dim ht As New Hashtable 
      ht.Items.Add("1", "Sunday") 
      ht.Items.Add("2", "Monday") 
      ht.Items.Add("3", "Tuesday") 
      ht.Items.Add("4", "Wednesday") 
      ht.Items.Add("5", "Thursday") 
      ht.Items.Add("6", "Friday") 
      ht.Items.Add("7", "Saturday") 

      For Each item In ht.Items 

       ListBox1.Items.Add(item.key) 
       ListBox1.Items.Add(item.value) 

      Next  

     End Sub 
    End Class 

執行的時候,我得到了以下的輸出:

在列表框中

1 Sunday 2 Monday 3 Tuesday 4 Wednesday 5 Thursday 6 Friday 7 Saturday 
1 Sunday 2 Monday 3 Tuesday 4 Wednesday 5 Thursday 6 Friday 7 Saturday 

爲什麼在我的代碼中使用單循環時出現兩次?我能做些什麼來解決我的問題?

回答

2

您需要從Button1聲明在ASPX代碼刪除onclick="Button1_Click"因爲後面的代碼已經指出Handles Button1.Click,否則Button1_Click將執行兩次:

<asp:Button ID="Button1" runat="server" Text="Button" /> 
+0

+1良好的漁獲物。雖然我不是100%確定這是真的。 –

+0

@TimSchmelter這是真的,我已經在Visual Studio中嘗試了上面的代碼,這正是原因。 – ekad

+0

非常感謝你....代碼完美地工作 – Belinda