在ASP.Net1.1中如果要實現兩個ListBox相互傳遞資料,比如有兩個ListBox ListBox1 和 ListBox2
<asp:ListBox id="ListBox1" style="Z-INDEX: 101; LEFT: 56px; POSITION: absolute; TOP: 72px" runat="server" Height="150px"
Width="100px">
<asp:ListItem Value="單片機">單片機</asp:ListItem>
<asp:ListItem Value="網路程式設計">網路程式設計</asp:ListItem>
<asp:ListItem Value="電子商務">電子商務</asp:ListItem>
<asp:ListItem Value="電腦圖形學">電腦圖形學</asp:ListItem>
<asp:ListItem Value="分布式系統">分布式系統</asp:ListItem>
<asp:ListItem Value="JSP技術">JSP技術</asp:ListItem>
</asp:ListBox>
<asp:ListBox id="ListBox2" style="Z-INDEX: 102; LEFT: 240px; POSITION: absolute; TOP: 72px" runat="server" Height="150px"
Width="100px"></asp:ListBox>
添加兩個Button button1 和 button2
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 168px; POSITION: absolute; TOP: 96px" runat="server" Width="60px" Text="
添加"></asp:Button>
<asp:Button id="Button2" style="Z-INDEX: 104; LEFT: 168px; POSITION: absolute; TOP: 152px" runat="server" Width="60px" Text="
刪除"></asp:Button>
給button1添加Click事件
private void Button1_Click(object sender, System.EventArgs e)
{
this.ListBox2.Items.Add(this.ListBox1.SelectedItem);
this.ListBox1.Items.Remove(this.ListBox1.SelectedItem);
}
button2的Click事件
private void Button2_Click(object sender, System.EventArgs e)
{
this.ListBox1.Items.Add(this.ListBox2.SelectedItem);
this.ListBox2.Items.Remove(this.ListBox2.SelectedItem);
}
假象 :表面上看基本的功能已經實現了,編譯運行,點擊"添加"按鈕ListBox1中選中的確實跑到ListBox2中了,再次點擊 出現錯誤“當SelectionMode 為 Single 時,ListBox 不能有多個選定項。”
改正方法1:修改ListBox1 和 ListBox2的SelectionMode 屬性 設定為 Multiple ,基本上可以實現,但是效果很次。
改正方法2:不修改ListBox1和ListBox2的SelectionMode 屬性 通過修改Button1_Click代碼
private void Button1_Click(object sender, System.EventArgs e)
{
this.ListBox2.Items.Add(this.ListBox1.SelectedItem);
this.ListBox2.SelectedIndex = 0;
this.ListBox1.Items.Remove(this.ListBox1.SelectedItem);
}
假象再次出現:當第一次點擊添加時,ListBox1中的選中項被添加到ListBox2中,並且ListBox1中的選定項以刪除,再次點擊,ListBox1中的項
再次添加到ListBox2中但是ListBox1中的選定項並為移除。我懷疑是SelectIndex的影響,在次修改代碼
private void Button1_Click(object sender, System.EventArgs e)
{
this.ListBox2.Items.Add(this.ListBox1.SelectedItem);
this.ListBox1.Items.Remove(this.ListBox1.SelectedItem);
this.ListBox2.SelectedIndex = 0;
}
這樣就可以了