Limit number of characters per line

Asked

Viewed 3,081 times

5

It is possible to limit the number of characters per line of a textbox multiline using Windows Forms C# and . Net 3.5?

  • You can do this without problems by limiting the WIDTH of the textbox. Based on the width will fit X characters in the line. Edit - Put the Acceptsreturn="True property"

4 answers

3


I created here an algorithm in the Keypress of the textbox, it limits the amount of characters in each line and forces the user to type enter to change the line:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    int tamanhoMaximoPorLinha = 10; 
    int[] keysLiberadas = { (int)Keys.Enter, (int)Keys.Back };

    int posicaoAtual = textBox1.SelectionStart;
    int linhaAtual = textBox1.GetLineFromCharIndex(posicaoAtual);

    if (textBox1.Lines.Length == 0)
    {
        if (textBox1.Text.Length > tamanhoMaximoPorLinha && !keysLiberadas.Contains((int)e.KeyChar))
        {
            e.Handled = true;
        }
    }
    else if (textBox1.Lines[linhaAtual].Length > tamanhoMaximoPorLinha && !keysLiberadas.Contains((int)e.KeyChar))
    {
        e.Handled = true;
    }
}

e.Handled = true; prevents typing that character.

2

You can overload (Override) in Appendtext and Text in a derived class.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class TextBoxExt : TextBox
    {
        new public void AppendText(string text)
        {
            if (Text.Length == MaxLength)
                return;
            base.AppendText(Text.Length + text.Length > MaxLength
                                ? text.Substring(0, (MaxLength - Text.Length))
                                : text);
        }

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set {
                base.Text = !string.IsNullOrEmpty(value) && value.Length > MaxLength
                                ? value.Substring(0, MaxLength)
                                : value;
            }
        }

        // Clearing top X lines with high performance
        public void ClearTopLines(int count)
        {
            if (count <= 0)
                return;
            if (!Multiline)
            {
                Clear();
                return;
            }

            var txt = Text;
            var cursor = 0;
            var brkCount = 0;

            while (brkCount < count)
            {
                int brkLength;
                var ixOf = txt.IndexOfBreak(cursor, out brkLength);
                if (ixOf < 0)
                {
                    Clear();
                    return;
                }
                cursor = ixOf + brkLength;
                brkCount++;
            }
            Text = txt.Substring(cursor);
        }
    }

    public static class StringExt
    {
        public static int IndexOfBreak(this string str, out int length)
        {
            return IndexOfBreak(str, 0, out length);
        }

        public static int IndexOfBreak(this string str, int startIndex, out int length)
        {
            if (string.IsNullOrEmpty(str))
            {
                length = 0;
                return -1;
            }
            var ub = str.Length - 1;
            if (startIndex > ub)
            {
                throw new ArgumentOutOfRangeException();
            }
            for (var i = startIndex; i <= ub; i++)
            {
                int intchr = str[i];
                switch (intchr)
                {
                    case 0x0D:
                        length = i < ub && str[i + 1] == 0x0A ? 2 : 1;
                        return i;
                    case 0x0A:
                        length = 1;
                        return i;
                }
            }
            length = 0;
            return -1;
        }
    }
}

1

I think creating an event textchanged and add an if gives account.

int jumpline = 40; //A cada 40 caracteres.
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{    
    if(textbox99.text.Length%jumpline ==0){
        textbox99.text += "\r\n";
    }
}
  • The code has a little problem, it returns to the beginning of the line when it reaches the end. But it helped me a lot to solve the problem.

0

Good afternoon Guys, I know the question has already been answered, but as these answers helped me to solve my problem, I leave here shared more information. I used these two events in sets for better resolution in my case. The First has the function of:

1. Set the maximum richtextbox size to 500.

2. Set the line size to 75.

3. If the word exceeds the length of the line, it is transferred to the line below.

4. If the maximum richtextbox size is exceeded an msg is displayed.

5. Restrict special characters by inserting space at the current position.

    private void rtxbAnaliseOp_TextChanged(object sender, EventArgs e)
    {
        bool ok = false;
        int i =  rtxbAnaliseOp.Text.Length -1;
        rtxbAnaliseOp.MaxLength = 500;
        try
        {   
            //tamanho do texto dividido pela quantidade de linhas
            if ((rtxbAnaliseOp.Text.Length / rtxbAnaliseOp.Lines.Length) >= 75)
            {
                //Nesse bloco é verificado o tamanho da palavra escrita após exceder o tamanho máximo da linha,
                //contando as casas decimais anteriores até achar o intervalo da palavra "espaço" o código insere Enter para pular de linha.
                while (ok == false)
                {
                    string x = rtxbAnaliseOp.Text.Substring(i, 1);
                    if (x == " ")
                    {
                        ok = true;
                        rtxbAnaliseOp.Text = string.Format(rtxbAnaliseOp.Text.Insert(++i, "\n"));
                        rtxbAnaliseOp.SelectionStart = rtxbAnaliseOp.Text.Length;
                    }
                    else
                        i--;
                }
            } 
            if (rtxbAnaliseOp.Text.Length >= 500)
            {                    
                // Verifica se o tamanho do texto é maior que a quantidade maxima de carateres disponíveis.
                if (rtxbAnaliseOp.Text.Length >= rtxbAnaliseOp.MaxLength)
                {
                    // Alerta o usuário que o maximo de carateres já foi escrito.
                    MessageBox.Show("Aleta! Você excedeu o limite de caracteres disponíveis");
                }                                        
            }

            //string pattern = @"[^0-9a-záéíóúàèìòùâêîôûãõç\s]";
            string pattern = @"[^0-9a-zA-Z\s]";
            string replacement = "";

            Regex rgx = new Regex(pattern);                
            string letra = rtxbAnaliseOp.Text.Substring(i, 1);

            //Verifica existência de caracteres especiais.
            if ( Regex.IsMatch(letra, pattern ))
            {
                MessageBox.Show("Aleta! Este campo não permite a inserção de Caracteres especiais");

                //Remove caracteres especiais Expressoes Regulares(Nesse caso nao aceita nada que não seja letras, numeros e espaço representado por "\s").
                rtxbAnaliseOp.Text = rgx.Replace(rtxbAnaliseOp.Text, replacement);
                rtxbAnaliseOp.SelectionStart = (rtxbAnaliseOp.Text.Length);
                //    rtxbAnaliseOp.Text = Regex.Replace(rtxbAnaliseOp.Text, "[^0-9a-zA-Z]", "");   
                //    rtxbAnaliseOp.Text = Regex.Replace(rtxbAnaliseOp.Text, pattern, replacement);
            }
        }
        catch (ArgumentOutOfRangeException)
        {
            rtxbAnaliseOp.Text = rtxbAnaliseOp.Text + string.Format("\n");
            rtxbAnaliseOp.SelectionStart = (rtxbAnaliseOp.Text.Length);
        }
        catch (DivideByZeroException)
        { }
    }

In this second case is the code of our friend:

Maicon Carraro

But in my case I had to change the verification of IF for:if (rtxbAnaliseOp.Text.Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar))) for the keyLiberada did not contain the method String.Contains.

    private void rtxbAnaliseOp_KeyPress(object sender, KeyPressEventArgs e)
    {
        //limita a quantidade de caracteres em cada linha e obriga ao usuário digitar enter para que mude de linha.
        int tamanhoMaximoPorLinha = 75;            
        int keyLiberada = (int)Keys.Enter;
        int posicaoAtual = rtxbAnaliseOp.SelectionStart;
        int linhaAtual = rtxbAnaliseOp.GetLineFromCharIndex(posicaoAtual);

        if (rtxbAnaliseOp.Lines.Length == 0)
        {
            if (rtxbAnaliseOp.Text.Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar)))
            {
                e.Handled = true;
            }
        }
        else if (rtxbAnaliseOp.Lines[linhaAtual].Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar)))
        {
            e.Handled = true;
        }
    }

Thanks again and I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.