Austin
Austin

Reputation: 154

Limiting words in a text box

I'm trying to create a text box in c# that will only contain 100 words and after the 100th word no other text can be input into the box.

Upvotes: 0

Views: 1248

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460158

A simple approach which might be inaccurate because it replaces consecutive white-spaces with one:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    string[] words = textBox1.Text.Split();
    int wordCount = words.Length;
    if (wordCount > 100)
        textBox1.Text = string.Join(" ", words.Take(100));
}

instead of the String.Join you could replace it with the old text:

private string oldText;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    string[] words = textBox1.Text.Split();
    int wordCount = words.Length;
    if (wordCount > 100)
        textBox1.Text = oldText;
    else
        oldText = textBox1.Text;
}

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9399

On the TextChanged event of the textbox, count the ocurrences of white spaces and line breaks. If they're greater than 99, don't allow the text to change. You'll have to keep a copy of its text in another variable so that you can revert to that if the user inputs thr 101th word.

Upvotes: 0

Related Questions