首页 文章

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

提问于
浏览
0

我想将数据有界列表框(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

    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();
         }
    }
    

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

    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集合添加简单字符串,此解决方案可用 .

  • 0

    单击按钮使用下面的代码 .

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

相关问题