2013年6月11日 星期二

ASP.NET ListBox 互傳

ASP.NET ListBox 互傳


HTML:
  1. <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
  2. <asp:ListItem>a</asp:ListItem>
  3. <asp:ListItem>b</asp:ListItem>
  4. <asp:ListItem>c</asp:ListItem>
  5. </asp:ListBox>
  6. <asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" />
  7.  
  8. <asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
  9. </asp:ListBox>
  10. <asp:Button ID="Button2" runat="server" Text="Del" onclick="Button2_Click" />

C#:
  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3. //單選add時用下列這行
  4. //ListBox2.Items.Add(ListBox1.SelectedItem);
  5.  
  6. //多選add用迴圈
  7. for (int i = 0; i < ListBox1.Items.Count; i++)
  8. {
  9. if (ListBox1.Items[i].Selected)
  10. {
  11. ListBox2.Items.Add(ListBox1.Items[i]);
  12. }
  13. }
  14. }
  15.  
  16. protected void Button2_Click(object sender, EventArgs e)
  17. {
  18. //單選del
  19. //ListBox2.Items.RemoveAt(ListBox2.SelectedIndex);
  20.  
  21. //多選del用迴圈
  22. for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
  23. {
  24. if (ListBox2.Items[i].Selected)
  25. {
  26. ListBox2.Items.RemoveAt(i);
  27. }
  28. }
  29. }

沒有留言:

張貼留言