Limit DevExpress-WinForms TextEdit text to its Width, not MaxLenght

2.4k views Asked by At


I need to limit the 1 line text entered in a XtraGrid repository editor to its column fixed width. I cannot use a monospaced font and MaxLenght because this field will be shown in a report.
In KeyPress event handler I tried to create a Label, put the string on it and compare its PreferedSize.Width to the column's Width. It almost worked well but is not easy to control Paste operations if I have to remove the exceeding chars (f.ex.: if I change the text value, the cursor jumps to 0).
I also tried using ActiveEditor.CreateGraphics.MeasureString but cannot get it to draw(measure) the text the same way DevExpress does.
If I could catch a Before_WordWrap event it would be a solution.
Thank you.

Edited: I see, I have 2 negative votes because someone consider that I did not have enough effort to find the answer by my own, but I consider that the answer was not easy! I won't delete the thread because I think it could be useful to others. Regards.

1

There are 1 answers

3
Ivan Ferrer Villa On BEST ANSWER

Thanks to DJ KRAZE's suggestion I got it.
On the EditValueChanging event of the repository TextEdit, I assign e.NewValue to a DevExpress Label and compare its PreferredSize.Widht with the column Width. If it is greater, I remove chars until it's smaller and assign the text to e.NewValue.
The cursor was jumping to 0, so (according to DevExpress FAQ) I had to do an Invoke to change TextEdit.SelectionStart property. Damn! VB-2008 doesn't accept anonymous methods and had to put it appart :)
Thanks.
Regards.

Private Sub RepositoryItemTextEditDescrip_EditValueChanging(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles RepositoryItemTextEditDescrip.EditValueChanging
    Static lbl As New DevExpress.XtraEditors.LabelControl
    Dim tx As DevExpress.XtraEditors.TextEdit = sender
    Dim s As String = e.NewValue.ToString.Split(vbCr)(0)
    lbl.Text = s
    lbl.Font = tx.Font
    If lbl.PreferredSize.Width >= colDescrip.Width - 15 Then
        Do Until lbl.PreferredSize.Width <= colDescrip.Width - 15 Or s.Length = 0
            s = s.Remove(s.Length - 1)
            lbl.Text = s
        Loop
    End If
    Dim i As Integer = tx.SelectionStart
    e.NewValue = s
    BeginInvoke(New Action(Of TextEdit, Integer)(AddressOf sbTxSelectIndx), New Object() {tx, i})
End Sub
Private Sub sbTxSelectIndx(ByVal tx As TextEdit, ByVal i As Integer)
    tx.Select(i, 0)
End Sub