views:

445

answers:

3

Hi,

I have a list box with items like A B C D E.
I also have two buttons Move UP and Move Down with it.
i have already made their properties false in the property window (F4).

Now i want when a user selects B or all the items below then my Move Up button should get enabled. It should be Disabled for A item

In the same way my Move Down button should be Enabled when the user selects D or all the items above it,It should be disabled for E.

Can u please provide me the right part of code to be written here.

Thanks....

A: 

Handle the SelectedIndexChanged event of the ListBox. If the SelectedIndex is greater than 0, enable "move up". If it is lesser than count - 1, enable "move down"

Thomas Levesque
A: 

Here's the code I use in listBox_SelectedIndexChanged:

this.moveUp.Enabled = this.listBox.SelectedIndex > 0;
this.moveDown.Enabled = this.listBox.SelectedIndex > -1 && listBox.SelectedIndex < listBox.Items.Count - 1;

Actually it's in a method called from there as the code's called when the dialog's initialised too.

ChrisF
A: 

I am doing a similar thing in my app. It also handles selection of multiple items and also checks if the multiple items that are selected are continuous or not.

Here's the code:

private bool SelectionIsContiguous(ListBox lb)
{
    for (int i = 0; i < lb.SelectedIndices.Count - 1; i++)
        if (lb.SelectedIndices[i] < lb.SelectedIndices[i + 1] - 1)
            return false;

    return true;
}

private void SetMoveButtonStates()
{
    if (this.listBox.SelectedIndices.Count > 0)
    {
        if (this.listBox.SelectedIndices.Count > 1 && !SelectionIsContiguous(this.listBox))
        {
            this.btnMoveUp.Enabled = false;
            this.btnMoveDown.Enabled = false;
            return;
        }

        int firstSelectedIndex = this.listBox.SelectedIndices[0];
        this.btnMoveUp.Enabled = firstSelectedIndex == 0 ? false : true;

        int lastIndex = this.listBox.Items.Count - 1;
        int lastSelectedIndex = this.listBox.SelectedIndices[this.listBox.SelectedIndices.Count - 1];
        this.btnMoveDown.Enabled = lastSelectedIndex == lastIndex ? false : true;
    }
}
Rashmi Pandit
Hi Rashmi,Thanks for the answer one more thing i wanted to ask. I want to select a file from my listbox Eg A given above.den i want to enable my button for this i have written this if (m_lbOPFfiles.SelectedIndex == 0) { m_BtnValidateInput.Enabled = true; }now on selecting A only my button is enables whereas i want on selecting any of files like B C D E it shud be enabled.i have written the above part in SelectIndex Changed Clik Event.Can u help out wats wrong??
crazy_itgal
If I understand your prob correctly, then you need to do this: ..... if (m_lbOPFfiles.SelectedIndex >= 0) { m_BtnValidateInput.Enabled = true; } .... hope this helps :)
Rashmi Pandit
Thanks,it worked...RegardsShweta..
crazy_itgal
Hmm ... good to know it worked. Btw, I know your name now ;)
Rashmi Pandit