使用字典将所选项目从列表框移动到另一个

时间:2014-03-04 19:57:03

标签: c# winforms dictionary listbox

enter image description here

我有两个列表框。左边的一个是从这段代码绑定的,值是一个字典:

    public void Roster_Shown(object sender, EventArgs e)
    {            
        SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Basketball;Integrated Security=True;User ID=apo;Password=nia2");
        con.Open();   
        SqlDataAdapter sda = new SqlDataAdapter("SELECT PLAYERS.ID, PLAYERS.NO, PLAYERS.SURNAME, PLAYERS.FIRSTNAME, CAST(PLAYERS.NO AS VARCHAR) + ' - ' + PLAYERS.SURNAME + ', ' + PLAYERS.FIRSTNAME AS PLAYER FROM PLAYERS INNER JOIN TEAMS ON PLAYERS.TEAM_ID = TEAMS.ID WHERE (TEAMS.NAME ='" + ht + "')ORDER BY PLAYERS.NO", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            listBox1.DataSource = dt;
            listBox1.DisplayMember = "PLAYER";
            listBox1.ValueMember = "ID";

            dictionary = new Dictionary<string,string>();
            for (int i = 0; i < dt.Rows.Count; i++)
                dictionary.Add(dt.Rows[i]["ID"].ToString(), dt.Rows[i]["PLAYER"].ToString()); 
 con.Close();
     } 

我想使用此词典将所选项目移动到第二个(右列表框2)。“ID”是值,“PLAYER”是显示的文本。我想使用两个按钮。一个用于将项目发送到右侧列表框2,另一个用于将所选项目移回第一个列表框1。

有任何建议吗?A尝试以下代码但不能正常工作.ADD()是移动项目的类,REMOVE()用于移回项目。

    private void button1_Click(object sender, EventArgs e)
    {
        ADD();
    }
    private void ADD()
    {
        listBox2.DataSource = new BindingSource(Roster_Shown.dictionary, null);
        listBox2.DisplayMember = "ID";
        listBox2.ValueMember = "PLAYER";
    } 

   private void button2_Click(object sender, EventArgs e)
    {
        REMOVE();
    }
    private void REMOVE()
    {
        int c = listBox2.Items.Count - 1;

        for (int i = c; i >= 0; i--)
        {
            if (listBox2.GetSelected(i))
            {
                listBox1.Items.Add(listBox2.Items[i]);
                listBox2.Items.RemoveAt(i);
            }
        }
    }

Image shows the result using the code from Dmitry 图像使用Dmitry的代码显示结果,但我只需要显示文本并保存id(可能在arraylist或字典中),因为我需要获取第二个列表的所有ID并将它们转移到另一个winform中的新列表框

将以下代码添加到Dmitry的代码中,该应用程序运行正常。

     public void button7_Click(object sender, EventArgs e)
    {
     if (listBox2.Items.Count > 4)
        {
            if (listBox4.Items.Count > 4)
            {

                Game game = new Game();

                foreach (ListItem item in listBox2.Items)
                { 
                    dictionaryHome.Add(item.Id, item.Name);
                    game.listBoxHome.DisplayMember = dictionaryHome.Values.ToString();
                    game.listBoxHome.ValueMember = dictionaryHome.Keys.ToString();
                    game.listBoxHome.DataSource = (from Values in    dictionaryHome.Values select Values).ToList();

                    //int itemId = item.Id;
                }
     this.Hide();

                game.Show();

            }
        }
       }

使用button7新表单中的新列表框将获取listbox2中的所有项目(右侧)并同时具有id(键)和value.Many感谢Dmitry !!!

1 个答案:

答案 0 :(得分:1)

MSDN

  

设置DataSource属性后,用户无法修改项集合。

试试这个示例代码:

internal sealed class TwoListsForm : Form
{
    private sealed class ListItem : IComparable<ListItem>
    {
        public int Id;
        public string Name;

        public int CompareTo(ListItem other)
        {
            return other == null ? 1 : Id.CompareTo(other.Id);
        }

        public override string ToString()
        {
            return Name;
        }
    }

    private System.Windows.Forms.ListBox lstLeft;
    private System.Windows.Forms.ListBox lstRight;
    private System.Windows.Forms.Button btnToRight;
    private System.Windows.Forms.Button btnToLeft;

    public TwoListsForm()
    {
        InitializeComponent();
    }

    public TwoListsForm(string ht)
    {
        InitializeComponent();

        using (SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Basketball;Integrated Security=True;User ID=apo;Password=nia2"))
        {
            con.Open();
            using (SqlDataAdapter sda = new SqlDataAdapter("SELECT PLAYERS.ID, PLAYERS.NO, PLAYERS.SURNAME, PLAYERS.FIRSTNAME, CAST(PLAYERS.NO AS VARCHAR) + ' - ' + PLAYERS.SURNAME + ', ' + PLAYERS.FIRSTNAME AS PLAYER FROM PLAYERS INNER JOIN TEAMS ON PLAYERS.TEAM_ID = TEAMS.ID WHERE (TEAMS.NAME ='" + ht + "')ORDER BY PLAYERS.NO", con))
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);

                object[] items = new object[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                    items[i] = new ListItem { Id = (int)dt.Rows[i]["ID"], Name = dt.Rows[i]["PLAYER"].ToString() };
                lstLeft.Items.AddRange(items);
            }
            con.Close();
        }
    }

    private void InitializeComponent()
    {
        this.lstLeft = new System.Windows.Forms.ListBox();
        this.lstRight = new System.Windows.Forms.ListBox();
        this.btnToRight = new System.Windows.Forms.Button();
        this.btnToLeft = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // lstLeft
        // 
        this.lstLeft.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)));
        this.lstLeft.FormattingEnabled = true;
        this.lstLeft.Location = new System.Drawing.Point(12, 12);
        this.lstLeft.Name = "lstLeft";
        this.lstLeft.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
        this.lstLeft.Size = new System.Drawing.Size(242, 264);
        this.lstLeft.Sorted = true;
        this.lstLeft.TabIndex = 0;
        // 
        // lstRight
        // 
        this.lstRight.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.lstRight.FormattingEnabled = true;
        this.lstRight.Location = new System.Drawing.Point(341, 12);
        this.lstRight.Name = "lstRight";
        this.lstRight.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
        this.lstRight.Size = new System.Drawing.Size(242, 264);
        this.lstRight.Sorted = true;
        this.lstRight.TabIndex = 1;
        // 
        // btnToRight
        // 
        this.btnToRight.Anchor = System.Windows.Forms.AnchorStyles.None;
        this.btnToRight.Location = new System.Drawing.Point(260, 77);
        this.btnToRight.Name = "btnToRight";
        this.btnToRight.Size = new System.Drawing.Size(75, 23);
        this.btnToRight.TabIndex = 2;
        this.btnToRight.Text = ">>>";
        this.btnToRight.UseVisualStyleBackColor = true;
        this.btnToRight.Click += new System.EventHandler(this.btnToRight_Click);
        // 
        // btnToLeft
        // 
        this.btnToLeft.Anchor = System.Windows.Forms.AnchorStyles.None;
        this.btnToLeft.Location = new System.Drawing.Point(260, 180);
        this.btnToLeft.Name = "btnToLeft";
        this.btnToLeft.Size = new System.Drawing.Size(75, 23);
        this.btnToLeft.TabIndex = 3;
        this.btnToLeft.Text = "<<<";
        this.btnToLeft.UseVisualStyleBackColor = true;
        this.btnToLeft.Click += new System.EventHandler(this.btnToLeft_Click);
        // 
        // TwoListsForm
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(595, 290);
        this.Controls.Add(this.btnToLeft);
        this.Controls.Add(this.btnToRight);
        this.Controls.Add(this.lstRight);
        this.Controls.Add(this.lstLeft);
        this.Name = "TwoListsForm";
        this.Text = "Two Lists Form";
        this.ResumeLayout(false);
    }

    private void btnToRight_Click(object sender, EventArgs e)
    {
        moveItems(lstLeft, lstRight);
    }

    private void btnToLeft_Click(object sender, EventArgs e)
    {
        moveItems(lstRight, lstLeft);
    }

    private void moveItems(ListBox from, ListBox to)
    {
        if (from.SelectedItems.Count == 0)
        {
            MessageBox.Show("Empty selection");
            return;
        }
        object[] tmp = new object[from.SelectedItems.Count];
        from.SelectedItems.CopyTo(tmp, 0);
        to.Items.AddRange(tmp);
        from.BeginUpdate();
        foreach (var item in tmp)
            from.Items.Remove(item);
        from.EndUpdate();
    }
}

用法:

using (TwoListsForm frm = new TwoListsForm(/* Your ht value */))
    frm.Show();

获取正确的列表框项目的ID:

foreach (ListItem item in lstRight.Items)
{
    int itemId = item.Id;
    ...
}

编辑:项目外观已更正。
EDIT2 :添加商品ID。