ASP.NET 1.1 ListBox的注意事项

在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;
}
这样就可以了

原文地址:https://www.cnblogs.com/interboy/p/607649.html