Hi there

I am working in Visual Studio 2005 Pro. I have created a WinForm with access to a SQL database. On the WinForm I have two listboxes, the displays DivisionCode and the other DivisionID both having the same DataSource but different DisplayMembers. They occupy the same space on the form with DivisionCode on top of DivisionID.

Whenever a user selects (or deselects) a value/index in the DivisionCode listbox, the corresponding value/index in the DivisionID must programmatically be selected/deselected.

The DivisionCode is used because it has more meaning for the user. The DivisionID is used for further lookups to the database.

How can I accomplish this, using the SelectedIndexChanged event?

Thanx in advance.

Recommended Answers

All 3 Replies

Got it sorted out.

if (this.lbDivisionCode.SelectedIndices.Count != 0)
                    {
                        for (int i = 0; i < this.lbDivisionCode.Items.Count; i++)
                        {
                            if (this.lbDivisionCode.GetSelected(i) == true)
                            {
                                this.lbDivisionID.SetSelected(i, true);
                            }
                            else
                            {
                                this.lbDivisionID.SetSelected(i, false);
                            }
                        }
...

If you don't need the ID to be visible you could look into the DisplayMember and ValueMembers when databinding to allow you to show the Code and have the ID as the value member.
Alternatively, you could consider using a datagridview, you can have as many columns as you like which can be visible to the user or hidden but still accessible in code.

Thanx Ryshad.

The code now looks like this:

private void lbDivisionCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                    if (this.lbDivisionCode.SelectedIndices.Count != 0)
                    {

                        this.DIDS = new int[this.lbDivisionCode.SelectedItems.Count];
                        int i = 0;
                        foreach (DataRowView DivID in lbDivisionCode.SelectedItems)
                        {
                            this.DIDS[i] = int.Parse(DivID["DivisionID"].ToString());
                            i++;
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Invalid Division selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.