Asp.NET 中两个listbox实现值相互传递

来源:互联网 发布:java手机qq 编辑:程序博客网 时间:2024/06/06 04:26

/// <summary>
 /// 增加listbox的值的方法
 /// </summary>
 /// <param name="sourceBox"></param>
 /// <param name="targetBox"></param>
 private void AddItemFromSourceListBox(ListBox sourceBox, ListBox targetBox)
 {
  foreach (ListItem item in sourceBox.Items)
  {
   if (item.Selected && !targetBox.Items.Contains(item))
   {
    targetBox.Items.Add(item);
   }
  }
 }

 /// <summary>
 /// 删除listbox的值的方法
 /// </summary>
 /// <param name="listControl"></param>
 private void RemoveSelectedItem(ListBox listControl)
 {
  while (listControl.SelectedIndex != -1)
  {
   listControl.Items.RemoveAt(listControl.SelectedIndex);
  }
 }

 

/// <summary>
 /// 增加
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnAdd_Click(object sender, EventArgs e)
 {
  if (ListBoxOldPaper.SelectedItem == null)
  {
   return;
  }
  else
  {
   AddItemFromSourceListBox(ListBoxOldPaper, ListBoxNewPaper);
   RemoveSelectedItem(ListBoxOldPaper);
   ListBoxNewPaper.SelectedIndex = ListBoxNewPaper.Items.Count - 1;   //设置当前选中项
   SetBtnEnable();  //设置按钮是否可用
  }
 }

/// <summary>
 /// 删除
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnDel_Click(object sender, EventArgs e)
 {
  if (ListBoxNewPaper.SelectedItem != null)
  {
   AddItemFromSourceListBox(ListBoxNewPaper, ListBoxOldPaper);
   RemoveSelectedItem(ListBoxNewPaper);
   ListBoxOldPaper.SelectedIndex = ListBoxOldPaper.Items.Count - 1;   //设置当前选中项
  }
  SetBtnEnable();
 }

/// <summary>
 /// 全部增加
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnAddAll_Click(object sender, EventArgs e)
 {
  foreach (ListItem item in ListBoxOldPaper.Items)
  {
   if (!ListBoxNewPaper.Items.Contains(item))
   {
    ListBoxNewPaper.Items.Add(item);
   }
  }
  ListBoxOldPaper.Items.Clear();  //清空原有的项
  SetBtnEnable();
 }

 

/// <summary>
 /// 全部删除
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnDelAll_Click(object sender, EventArgs e)
 {
  ListBoxOldPaper.Items.Clear();  //先清空源集合的所有项
  ListBoxNewPaper.Items.Clear();    //清空新集合的所有项
  GetOldPaperListBoxDataSource();   //重新绑定源集合的项
  SetBtnEnable();
 }

原创粉丝点击