开发者

Transfer listBox item to another listBox (Winforms C#)

I have two listBoxes. The first listbox contains the list of traffic violations. When you click the add button and execute the code, the listbox2 got this item "ListBoxTest.Violation", not the item being displayed from the listBox1...

What is wrong with my code?

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 v开发者_C百科iolationList.
            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; }
        }
    }
}


Type cast the selected item to Violation. This should fix the problem. Edit: I have modified the code to fix the issue.

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


Make sure listbox2 has the same settings as listbox1, e.g. listbox2.ValueMember, listbox2.DisplayMember..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜