kenny
kenny

Reputation: 1247

C# ListView prevent selection

I'm in a situation with a multiple select ListView where a maximum of three items may be selected. I currently have following code

    private void grassListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        string landType = this.grassLandTypeComboBox.Text;
        if (this.grassListView.SelectedIndices.Count < 4)
        {
            ArrayList selectedGrassTextures = (ArrayList)((Hashtable)this.paintGrass[landType])["textures"];
            selectedGrassTextures.Clear();
            foreach (ListViewItem listViewItem in this.grassListView.SelectedItems)
            {
                selectedGrassTextures.Add(listViewItem.Text);
            }
        }
        else
        {
           MessageBox.Show("You cannot have more than 3 grasses selected for any given attribute type");
        }
    }

this code works and in the end my selectedGrassTextures HashTable has only three elements. However the GUI still shows the element as (selected/focused?). So to the user it seems that it is still selected. So I like to prevent this, is there anything I can use to either find the last element clicked on and put the selection of it or the focus. Another way would be if there is an event Before SelectedIndexChanged that I can move my < 4 check into. Is there such an event, I thought ListView.SelectedIndexChanging, but in my IDE it shows up as not existing. I'm using visual studio express and framework 3.5, can't use 4.5 for what I'm doing.

Upvotes: 0

Views: 716

Answers (1)

TaW
TaW

Reputation: 54433

Put this in the ItemSelectionChanged event:

private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (listView1.SelectedItems.Count > 4) e.Item.Selected = false;
    }

Upvotes: 1

Related Questions