将选定项从绑定列表框添加到未绑定列表框

时间:2015-02-05 07:24:17

标签: c# listbox windows-applications

我想将数据有界列表框(listbox1)中的所选项目添加到另一个列表框(listbox2)

以下是按钮点击事件的代码。

private void btnrgt_Click(object sender, EventArgs e)
{
     string x = listBox1.SelectedItem.ToString();
     listBox2.Items.Add(x.ToString());
     txttestno.Text = listBox2.Items.Count.ToString();
}

当我运行此代码时,System.data.datarowview会显示在listbox2中。

请帮助。 提前谢谢你。

2 个答案:

答案 0 :(得分:0)

点击按钮使用以下代码。

protected void btnGo_Click(object sender,EventArgs e) {
    string x = ListBox1.SelectedItem.Text;
    ListBox2.Items.Add(x);
}

答案 1 :(得分:0)

ListBox数据源绑定到DataTable时,ListBox中的每个项目都是DataRowView,而不是简单的字符串。在ListBox中,您会看到显示的字符串,因为您使用该DataRowView中的列名称设置了ListBox的DisplayMember属性。

因此,获取当前SelectedItem不返回字符串,但DataRowView和DataRowView调用ToString()将返回类的完整限定名称(System.Data.DataRowView)。

你需要这样的东西

private void btnrgt_Click(object sender, EventArgs e)
{
     DataRowView x = listBox1.SelectedItem as DataRowView;
     if ( x != null)
     {
          listBox2.Items.Add(x["NameOfTheColumnDisplayed"].ToString());
          txttestno.Text = listBox2.Items.Count.ToString();
     }
}

修改
目前尚不清楚以下评论中所述错误的来源是什么,但是如果该项目存在于第二个列表框中,您可以尝试避免将第一个列表框中的项目添加到第二个列表框中,并使用此类代码

private void btnrgt_Click(object sender, EventArgs e)
{
     DataRowView x = listBox1.SelectedItem as DataRowView;
     if ( x != null)
     {
          string source = x"NameOfTheColumnDisplayed".ToString();
          if(!listbox2.Items.Cast<string>().Any(x => x == source))
          {
              listbox2.Items.Add(source);
              txttestno.Text = listBox2.Items.Count.ToString();
          }
     }
}

如果您的第二个列表框确实已填充,则将此简单字符串添加到其Items集合中,此解决方案可用。