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

Add selected item from a bound listbox to a unbound listbox

我想将选定的项目从数据绑定列表框 (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 显示在列表框 2 中。

请帮忙。 提前谢谢你。

点击按钮使用下面的代码。

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

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

因此,获取当前 SelectedItem 不是 return 字符串而是 DataRowView 并为 DataRowView 调用 ToString() return 的完整限定名称class (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 集合添加简单字符串,则此解决方案有效。