James Carlyle-Clarke
James Carlyle-Clarke

Reputation: 868

C# ListView Label Edit - control selected text

I am looking at the .Net Framework ListView (I've been trying BetterListView, the express version, and keep running up against things I can't do, so I figure I might as well run up against things I can't do in the better documented MS ListView!) and there's something that's stumping me.

I'd like the items to be editable, but I would like, when editing starts, for the selected text to be only part of the item text rather than all of it.

An example of this would be in Windows Explorer, when you have file extensions visible, and you start to rename a file - the file name is selected (blue background) but the file extension is not, such that if the user starts to type immediately then the name will be replaced but the extension stays as is.

I can think of workarounds, but wondered if there's any way to do that.

Upvotes: 6

Views: 2822

Answers (3)

James Carlyle-Clarke
James Carlyle-Clarke

Reputation: 868

One long trawl through the appropriate messages, and the answer is...

private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
    IntPtr editWnd = IntPtr.Zero;
    editWnd = SendMessage(listView1.Handle, LVM_GETEDITCONTROL, 0, IntPtr.Zero);
    int textLen = Path.GetFileNameWithoutExtension(listView1.Items[e.Item].Text).Length;
    SendMessage(editWnd, EM_SETSEL, 0, (IntPtr) textLen);
}

public const int EM_SETSEL = 0xB1;
public const int LVM_FIRST = 0x1000;
public const int LVM_GETEDITCONTROL = (LVM_FIRST + 24);

[DllImport("user32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, IntPtr order);

That does exactly what I was after. Thanks for the other responders taking the time to answer.

Upvotes: 9

ScruffyDuck
ScruffyDuck

Reputation: 2666

Take a look at ObjectListView here: http://objectlistview.sourceforge.net/cs/index.html It is easy to use, very flexible and for the most part free.

Upvotes: 0

Mert
Mert

Reputation: 6572

You can use gridview for this. GridView has ItemEdit. also you can try some components like telerik or devexpress..

Upvotes: 0

Related Questions