日期:2014-05-18  浏览次数:20445 次

可多选ListBox数据绑定后,为何Selected始终为第一项?
一、问题背景描述:

从数据库调出数据:人名,电话(DataSet)绑定到ListBox1(支持多选)。

多选后,点击按钮Button1,期望:能够把ListBox1的选中项全部移到ListBox2。

二、问题症状:

当点击Button1时,只能够把第一项放入TextBox2,不管选的是什么,永远是将第一项移过去!


二、几个说明:

1. 数据绑定部分已经放入if(!IsPostBack),不是页面回发问题

2. 如果不用数据绑定的方式,而用手动直接设置ListBox1的项或者用编程方式添加ListBox1项都可以正常将选中的多个元素移动到ListBox2。

三、附部分代码

Page_Load
  if (!IsPostBack)
  {
  //直接调用自定方法BindTextBox1().
  BindTextBox1(); //只要绑定上去的就无法按要求移动数据

  //这样写入是能够按要求将TextBox1中的被选项移到TextBox2中的,但只要用绑定数据就不行。
  //this.ListBox1.Items.Add(new ListItem("a","a"));
  //this.ListBox1.Items.Add(new ListItem("b","b"));
  //this.ListBox1.Items.Add(new ListItem("c","c"));
  }

BindTextBox1()
{
  myDs = myDataBase.GetDataSet(sql,conn);//数据集取得没有任何问题
  this.ListBox1.DataSource = myDs;
  this.ListBox1.DataTextField = "姓名_电话";
  this.ListBox1.DataValueField = "联系电话1";
  this.ListBox1.DataBind();
}

Button1_Click

  //无论使用注释内的for还是后面的while都不能成功将数据绑定后的TextBox1数据按要求转移到TextBox2内
  //for (int i = 0; i < ListBox1.Items.Count; i++)
  //{
  // if (ListBox1.Items[i].Selected)
  // { 
  // ListBox2.Items.Add(new ListItem(ListBox1.Items[i].Text,ListBox1.Items[i].Value));
  // ListBox1.Items.RemoveAt(i);
  // i--;
  // }
  //}

  while (ListBox1.SelectedIndex > -1)
  {
  if (ListBox1.SelectedItem.Selected)
  {
  ListBox2.Items.Add(ListBox1.SelectedItem);
  }
  ListBox1.Items.Remove(ListBox1.SelectedItem);
  }

四、问题何在?

  是什么问题?不出任何错,就是无法达到我的要求。

------解决方案--------------------
C# code
 while (ListBox1.SelectedIndex > -1)
            {
                if (ListBox1.SelectedItem.Selected)
                {
                    ListBox2.Items.Add(ListBox1.SelectedItem);
                }
                ListBox1.Items.Remove(ListBox1.SelectedItem);
            }
            foreach 判断每个选择项是否被选上

------解决方案--------------------
可以的啊
例子
HTML code
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<script runat="server">

  protected void Button1_Click(object sender, EventArgs e)
  {
    ListBox2.Items.Clear();
    for (int i = 0; i < ListBox1.Items.Count; i++)
    {
      if (ListBox1.Items[i].Selected)
      {
        ListBox2.Items.Add(ListBox1.Items[i].Value);
      }
    }
  }

  void BindTextBox1()
  {
    //模拟下

    ListBox1.Items.Add("A");
    ListBox1.Items.Add("B");
    ListBox1.Items.Add("C");
    ListBox1.Items.Add("D");
    ListBox1.Items.Add("E");
  }

  protected void Page_Load(object sender, EventArgs e)
  {

    if (!IsPostBack)
    {

      BindTextBox1();
    }
  }
</script>
<head>
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
  <asp:ListBox ID="ListBox2" runat="server" SelectionMo