您好,登录后才能下订单哦!
这篇文章将为大家详细讲解有关如何对ListBox实现添加移除操作,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
															前台代码: 
代码如下:
<div> 
<asp:ListBox ID="ListBox1" runat="server" Height="123px" Width="113px" SelectionMode="Multiple"> 
<asp:ListItem>tom</asp:ListItem> 
<asp:ListItem>jion</asp:ListItem> 
<asp:ListItem>j</asp:ListItem> 
<asp:ListItem>l</asp:ListItem> 
<asp:ListItem>k</asp:ListItem> 
</asp:ListBox> 
 <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="添加" /> 
  
<asp:Button ID="btnRemove" runat="server" Text="移除" OnClick="btnRemove_Click" /> 
 <asp:ListBox ID="ListBox2" runat="server" Height="123px" SelectionMode="Multiple" Width="113px"></asp:ListBox> 
</div> 
后台代码: 
代码如下:
protected void btnAdd_Click(object sender, EventArgs e) 
{ 
#region listbox添加记录的一种错误理解 
//选择多条记录的时候,会有一条没有被添加,这是因为当一条记录被移除后,原来的第二条记录的index为0 
//for (int i = 0; i < ListBox1.Items.Count; i++) 
//{ 
// if (ListBox1.Items[i].Selected == true) 
// { 
// ListBox2.Items.Add(ListBox1.SelectedValue); 
// ListBox1.Items.Remove(ListBox1.SelectedValue); 
// } 
//} 
#endregion 
#region listbox利用index索引号进行添加的简单写法 
//while (0 <= ListBox1.SelectedIndex) 
//{ 
// ListBox2.Items.Add(ListBox1.SelectedItem); 
// ListBox1.Items.Remove(ListBox1.SelectedItem); 
//} 
#endregion 
#region listbox的另一种成功添加方法 
List<ListItem> list = new List<ListItem>(); 
for (int i = ListBox1.Items.Count - 1; i >= 0; i--) 
{ 
if (ListBox1.Items[i].Selected == true) 
{ 
list.Add(ListBox1.Items[i]); 
ListBox1.Items.Remove(ListBox1.Items[i]); 
} 
} 
for (int i = 0; i <=list.Count - 1; i++) 
{ 
ListBox2.Items.Add(list[i]); 
} 
#endregion 
} 
protected void btnRemove_Click(object sender, EventArgs e) 
{ 
while (0 <= ListBox2.SelectedIndex) 
{ 
ListBox1.Items.Add(ListBox2.SelectedItem); 
ListBox2.Items.Remove(ListBox2.SelectedItem); 
} 
} 
关于“如何对ListBox实现添加移除操作”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。