将列表框项传输到另一个列表框 (Winforms C#)

本文关键字:列表 Winforms 传输 另一个 | 更新日期: 2023-09-27 17:55:37

我有两个列表框。第一个列表框包含流量违规列表。当您单击添加按钮并执行代码时,listbox2 将获得此项"ListBoxTest.Violation",而不是从 listBox1 中显示的项...

我的代码有什么问题?

namespace ListBoxTest
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        private List<Violation> violationList = new List<Violation>();
        public MainForm()
        {
            InitializeComponent();
        }
        void MainFormLoad(object sender, EventArgs e)
        {
            LoadViolations(); // Initialize and add violations to violationList.
            listBox1.DataSource = violationList; // Set the DataSource property.
            listBox1.ValueMember = "Code";
            listBox1.DisplayMember = "Description";
        }
        void LoadViolations()
        {
            Violation violation;
            violation = new Violation("001", "Beating the red light");
            violationList.Add(violation);
            violation = new Violation("002", "Exceeding posted speed limit on the road");
            violationList.Add(violation);
            violation = new Violation("003", "Driving a vehicle without license to drive");
            violationList.Add(violation);
            violation = new Violation("004", "Driving a non registered vehicle");       
            violationList.Add(violation);
            violation = new Violation("005", "Vehicle has no plate number");
            violationList.Add(violation);
        }
        void BtnAddClick(object sender, EventArgs e)
        {
            listBox2.Items.Add(listBox1.SelectedItem); // Add item from listBox1 to listBox2;
        }
    }
    /// <summary>
    /// Violation Class
    /// Properties: Code, Description
    /// </summary>
    public class Violation
    {
        private string _code;
        private string _description;
        public Violation(string code, string description)
        {
            _code = code;
            _description = description;
        }
        public String Code
        {
            get { return _code; }
            set { _code = value; }
        }
        public String Description
        {
            get { return _description; }
            set { _description = value; }
        }
    }
}

将列表框项传输到另一个列表框 (Winforms C#)

类型将所选项目强制转换为"冲突"。这应该可以解决问题。编辑:我已经修改了代码以解决此问题。

private void AddClick(object sender, EventArgs e)
{
    // Set the DataSource property.          
    listBox2.ValueMember = "Code";
    listBox2.DisplayMember = "Description";    
    listBox2.Items.Add((Violation)listBox1.SelectedItem); 
}    

确保listbox2具有与listbox1相同的设置,例如 listbox2.ValueMemberlistbox2.DisplayMember..