na_sacc
na_sacc

Reputation: 878

How to keep the Selected property true when clicked a not exist row in ListView?

My ListView have to keep the Selected property true unless Light and Time value changed. (Because the ListView should remain in this state and Enabled should change to false.)

enter image description here

When I click outside ListView, the Selected property stays true. But, when I click a 'not exist' row of ListView, the Selected property doesn't stay true.

enter image description here

To solve this problem, I wrote a code in ListView_Click event, but ListView_Click event only occurs about rows with values.

What shoud I do?

Upvotes: 1

Views: 134

Answers (2)

IV.
IV.

Reputation: 9463

One way to suppress suppress the click behavior under those conditions is to make a custom ListViewEx class that overrides WndProc and performs a HitTest when the mouse is clicked. (You'll have to go to the designer file and swap out the ListView references of course.)

class ListViewEx : ListView
{
    const int WM_LBUTTONDOWN = 0x0201;
    protected override void WndProc(ref Message m)
    {
        if(m.Msg == WM_LBUTTONDOWN)
        {
            if (suppressClick())
            {
                m.Result = (IntPtr)1;
                return;
            }
        }
        base.WndProc(ref m);
    }
    private bool suppressClick()
    {
        var hitTest = HitTest(PointToClient(MousePosition));
        if ((hitTest.Item == null) || string.IsNullOrEmpty(hitTest.Item.Text))
        {
            return true;
        }
        return false;
    }
}

test result

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125302

If you want to keep the selection locked to a specific item, and want to keep it highlighted no matter whether or not the form or the control has focus, do the following:

First, set listView1.HideSelection = false.

Then handle ItemSelectionChanged and set the backcolor, forecolor and selected status accordingly:

int LockSelectionToIndex = 0; //Lock selection to index 0
private void listView1_ItemSelectionChanged(object sender,
    ListViewItemSelectionChangedEventArgs e)
{
    e.Item.Selected = (e.ItemIndex == LockSelectionToIndex);
    if (e.Item.Selected)
    {
        e.Item.BackColor = SystemColors.Highlight;
        e.Item.ForeColor = SystemColors.HighlightText;
    }
    else
    {
        e.Item.BackColor = SystemColors.Window;
        e.Item.ForeColor = SystemColors.WindowText;
    }
}

Upvotes: 1

Related Questions