Introduction
This article describes how to limit the number of characters that a user can enter into an edit control of a list view control that is set for detail view. By default there is no simple straightforward way to do this, like a property to set.
Using the code
The default ListView
control that .NET has doesn't have the ability for you to limit the amount of text than you can enter into the edit control. This is easily solved...
First you have to include a using
statement for System.Runtime.InteropServices
. This allows you to use the DllImport
attribute. Next you can define a call into the Windows API using that attribute.
[DllImport("user32.dll", CharSet=CharSet.Ansi)]
private static extern IntPtr SendMessage(IntPtr hWnd,
int msg, int len, IntPtr order);
Add an event for the BeforeLabelEdit
to your list view.
private void lvListView_BeforeLabelEdit(object sender,
System.Windows.Forms.LabelEditEventArgs e)
{
IntPtr editWnd = IntPtr.Zero;
editWnd = SendMessage(lvListView.Handle,
LVM_GETEDITCONTROL, 0, IntPtr.Zero);
SendMessage(editWnd, EM_LIMITTEXT, 6, IntPtr.Zero);
}
Finally add the couple of constants that the above function is using.
private const int EM_LIMITTEXT = 0xC5;
private const int LVM_FIRST = 0x1000;
private const int LVM_GETEDITCONTROL = (LVM_FIRST + 24);
That's it. This little article I hope helps repay all the programmers that contributed articles that I have used throughout the last few years.