摘要:ListBox資料互傳
因為要做AJAX的效果 所以要加入ScriptManager與UpdatePanel
頁面上有兩個ListBox : ListBox1 與ListBox2
ListBox1透過Sqldatasource資料繫結 在頁面開啟時取得資料
接著透過兩個button將繫結的資料在兩個ListBox傳輸 不會重覆
.aspx
<head runat="server">
<title>未命名頁面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr>
<td rowspan=2><asp:ListBox ID="ListBox1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="LastName"
DataValueField="EmployeeID" Height="300px" Width="250px"
SelectionMode="Multiple"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName] FROM [Employees]">
</asp:SqlDataSource>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="->" />
</td>
<td rowspan=2>
<asp:ListBox ID="ListBox2" runat="server" Height="300px" Width="250px"
SelectionMode="Multiple">
</asp:ListBox>
</td>
<td rowspan=2>
<asp:TextBox ID="TextBox1" runat="server" Width="317px"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="取listbox2的值" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button2" runat="server" Text="<-" />
</td>
</tr>
</table>
</ContentTemplate></asp:UpdatePanel></div></form></body></html>
.vb
'ListBox1資料傳往ListBox2
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim item As New ListItemCollection
If Me.ListBox1.SelectedIndex <> -1 Then
For i As Integer = 0 To Me.ListBox1.Items.Count - 1
If Me.ListBox1.Items(i).Selected = True Then
item.Add(Me.ListBox1.Items(i))
End If
Next
UpdateListBox(Me.ListBox2, Me.ListBox1, item)
End If
End Sub
'ListBox2資料傳往ListBox1
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
Dim item As New ListItemCollection
If Me.ListBox2.SelectedIndex <> -1 Then
For i As Integer = 0 To Me.ListBox2.Items.Count - 1
If Me.ListBox2.Items(i).Selected = True Then
item.Add(Me.ListBox2.Items(i))
End If
Next
UpdateListBox(ListBox1, ListBox2, item)
End If
End Sub
'修改ListBox資料 帶入增加List及減少List的ListBox 並且將List的集合帶入
Private Sub UpdateListBox(ByVal addList As ListBox, ByVal removeList As ListBox, ByVal itemList As ListItemCollection)
For i As Integer = 0 To itemList.Count - 1
addList.Items.Add(itemList(i))
removeList.Items.Remove(itemList(i))
Next
End Sub
'嘗試取得ListBox2的資料
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Me.TextBox1.Text = ""
For i As Integer = 0 To Me.ListBox2.Items.Count - 1
Me.TextBox1.Text += Me.ListBox2.Items(i).Value & Me.ListBox2.Items(i).Text & ";"
Next
End Sub
Protected
Protected