c# - CopyListBoxItem 从一个 ListBox 到另一个

标签 c# .net winforms listbox

我有两个列表框。我想将 SelectedItem 从第一个 ListBox 复制到第二个。

为什么这段代码不起作用?

    private void frm_addDispatchBoard2_Load(object sender, EventArgs e)
    {
        using(propertiesManagementDataContext db = new propertiesManagementDataContext())
        {
            var Buildings = db.Buildings.Select(q => new { q.BuildingLandNumber, q.BuildingId });

            listBox_allBuildings.DataSource = Buildings;
            listBox_allBuildings.DisplayMember = "BuildingLandNumber";
            listBox_allBuildings.ValueMember = "BuildingId";
        }          
    }

    private void btn_addBuilding_Click(object sender, EventArgs e)
    {
        if(listBox_allBuildings.SelectedIndex > 0)
        {
            listBox_selectedBuildings.Items.Add(listBox_allBuildings.SelectedItem);            
        }
    }

我得到的结果:

enter image description here

最佳答案

试试这个 我不确定你为什么要寻找一个 Contains 但如果你真的需要看看 SelectedValueSelectedItem

之间的区别

Use this code right here as a test to see if the expected value shows up in a MessageBox

string selected = listBox_allBuildings.GetItemText(listBox_allBuildings.SelectedValue);    
MessageBox.Show(selected);

这应该可以帮助您查看右侧列表框中的值

private void btn_addBuilding_Click(object sender, EventArgs e)
{
    if(listBox_allBuildings.SelectedIndex != -1)
    {
       var selected = listBox_allBuildings.GetItemText(listBox_allBuildings.SelectedValue);     
       listBox_selectedBuildings.Items.Add(selected);
    }
}

关于c# - CopyListBoxItem 从一个 ListBox 到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25332311/

相关文章:

c# - 数据绑定(bind)不包含具有名称的属性

c# - 在 DataGridView 上托管自定义控件,这些控件从 DataTable 填充数据

.net - 表单背景颜色设置为淡色

c# - 我如何知道对象属性是否具有默认值?

c# - json.net,将新对象/项目添加/附加到现有 JSON 对象中

c# - 如何序列化 IList<T>?

c# - 如何使用没有关联前缀的命名空间在 C# 中读取 XML 文档

c# - 如何加载类型库以在 C# 中解析它?

c# - 仅显示来自 ApplicationException 的消息

c# - 由于语言要求,如何在单独的线程上打开表单