简体   繁体   中英

how to add selected item from one listBox to another listBox

i have 16 Items in listBox1 and one button "button1", i need to to be able to move the selected Item from listBox1 to listBox2 when a button is pressed. currently my code is

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace courseworkmodule
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            String workingDir = Directory.GetCurrentDirectory();
            XmlTextReader textReader = new XmlTextReader(workingDir + @"\modules.xml");

            Console.WriteLine("BaseURI:" + textReader.BaseURI);
            textReader.Read();

            while (textReader.Read())
            {
                textReader.MoveToElement();

                if (textReader.Name == "Name")
                {

                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;

                    if (nType == XmlNodeType.Text)
                    {
                        listBoxAllModules.Items.Add(textReader.Value);
                    }
                }
            }

            Console.ReadLine();
            textReader.Close();
        }

        public void button1_Click(object sender, EventArgs e)
        {
            listBoxStudentModules.Items.Add(listBoxAllModules.SelectedItem); 
        } 

        private void Form1_Load_1(object sender, EventArgs e)
        {

        }

        private void listBoxAllModules_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

where listBoxAllModule is listBox1 and listBoxStudentModule is listBox2 thanks in advance for any help

You can make it explicit to see what is going on:

 string value = listBoxAllModules.SelectedItem.Value; 
 string text = listBoxAllModules.SelectedItem.Text;  
 ListItem item = new ListItem (); 
 item.Text = text;                
 item.Value = value;
 listBoxStudentModules.Items.Add(item); 

listBoxAllModules.Items is a ListBox.ObjectCollection . You are trying to use it as a method:

listBoxAllModules. Items( listBoxAllModules.SelectedItem )

This will not work. You are missing the Add call. Should be .Items.Add() . You should be able to just add the SelectedItem as TechnologRich shows:

listBoxStudentModules.Items.Add(listBoxAllModules.SelectedItem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM