Listview, reselect old selection C#

Y

youngie

I've got a listview on a form in report style. It's populated with 40
item. I want to prevent the used clicking on some items, and if the
user clicks on one of these items I want the selection to revert back
to the old selection, hideselection property if false, listview is
single select.

In the OnSelectedChange() handler I test to see if the newly selected
item is a selectable one, if it's not, I try to change the selection
like so.

private void OnSelectedItemChanged(object sender, System.EventArgs e)
{
if( listView1.SelectedItems.Count != 0 )
{
int idx = listView1.SelectedItems[0].Index;
bool ret = execScript.isExecutable(idx);
if(ret == false)
{
listView1.Items[execScript.getCurrentExecNum()].Selected = true;
listView1.Select();
listView1.EnsureVisible(execScript.getCurrentExecNum());
listView1.Focus();
}
}

This doesn't work.
Neither does posting a user message to this function by overriding the
WndProc and calling Win32

[DllImport("user32.Dll")]
public static extern Int32 PostMessage(IntPtr Handle, Int32
ConnectionType, IntPtr wParam, IntPtr lParam);

ResetSelection()
{
listView1.Items[execScript.getCurrentExecNum()].Selected = true;
listView1.Select();
listView1.EnsureVisible(execScript.getCurrentExecNum());
listView1.Focus();
}

Neither does using a delegate like this

listView1.BeginInvoke(new
OnSelectedItemChangedDelegate(ResetSelection),null);

Neither does adding a filter on to the listview control and trapping
the LVN_ITEMCHANGING or LVN_ITEMCHANGED message in the WM_NOTIFY.

Interesting to note though if I add a button to the form and call my
ResetSelection() function it works fine.

Three days I've spent on this. Can anyone help?

Thanks

Youngie...
 
H

Howard Swope

Try this:

ListViewItem selectedItem = null;



private void listView1_MouseUp(object sender, MouseEventArgs e)

{

ListViewItem item = listView1.GetItemAt(e.X,e.Y);

if (item != null && item.Checked)

{

item.Selected = false;

if (selectedItem != null)

selectedItem.Selected = true;

}

}



private void listView1_MouseDown(object sender, MouseEventArgs e)

{

if (listView1.SelectedItems.Count == 1)

selectedItem = listView1.SelectedItems[0];

else

selectedItem = null;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top