Adding a textbox in a datatemplate with MaxLength has issues

2 posts, 0 answers
  1. Shilpi
    Shilpi avatar
    18 posts
    Member since:
    Jan 2012

    Posted 20 Nov 2012 Link to this post

    HI -

    I created a GridView Cell template with a TextBox with MaxLength = 30, When I reach the 30th character, and I try to type in a letter the focus moves to the next column, is that by design?

    <telerik:GridViewDataColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox VerticalAlignment="Center" MaxLength="30" HorizontalAlignment="Stretch" Text="{Binding NickName, Mode=TwoWay}" TextWrapping="Wrap" MaxWidth="200"/>
                            </DataTemplate>
                        </telerik:GridViewDataColumn.CellTemplate>

    I would think that the focus should stay on the current column (textBox) and not let me type after the 30th character?

    Thanks, Shilpi
  2. Nedyalko Nikolov
    Admin
    Nedyalko Nikolov avatar
    871 posts

    Posted 21 Nov 2012 Link to this post

    Hello,

    The problem comes from the fact that TextBox does not handle KeyDown event (when MaxLength is reached), therefore KeyDown event is handled by RadGridView and RadGridView takes the appropriate action (put the current cell in edit mode, navigates to other cell, ...). You can easily handle this case with a few lines of code:

    <DataTemplate>
                                <TextBox VerticalAlignment="Center" MaxLength="30" HorizontalAlignment="Stretch"
                                         Text="{Binding Name, Mode=TwoWay}" KeyDown="TextBox_KeyDown"
                                         TextWrapping="Wrap" MaxWidth="200"/>
                            </DataTemplate>

    And the code behind:

    private void TextBox_KeyDown(object sender, KeyEventArgs e)
            {
                TextBox textBox = sender as TextBox;
                if (e.Key == Key.Tab)
                {
                    return;
                }
     
                if (textBox.Text.Length == 30)
                {
                    e.Handled = true;
                }
            }

    Let me know if this does not help.

    Regards,
    Nedyalko Nikolov
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Back to Top