Hi
I'm very new to programming and I'm learning C# for the first time with no experience.
I just finished designing a program which counts the vowels in a sentence.
Now I would like to count the vowels while typing it to the text box. I'm wondering what event/events is/are being used.

I'm not quite sure if it's something to do with "KeyPress" or "KeyUp".

I would appreciate your help. Thanks.
Here is my code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCount_Click(object sender, EventArgs e)
        {
            string yourSentence;
            yourSentence = textBox1.Text.ToLower().Trim();
            
            int counta = 0;
            int counte = 0;
            int counti = 0;
            int counto = 0;
            int countu = 0;

            int j = counta + counte + counti + counto + countu;
           

            foreach (char v in yourSentence)
            {
                switch (v)
                {
                    case 'a':
                        counta++;
                        j++;
                        break;

                    case 'e':
                        counte++;
                        j++;
                        break;

                    case 'i':
                        counti++;
                        j++;
                        break;

                    case 'o':
                        counto++;
                        j++;
                        break;

                    case 'u':
                        countu++;
                        j++;
                        break;
                }
            }

            listBox1.Items.Add("There are " + counta.ToString().Trim() + " a's in the sentence");
            listBox1.Items.Add("There are " + counte.ToString().Trim() + " e's in the sentence");
            listBox1.Items.Add("There are " + counti.ToString().Trim() + " i's in the sentence");
            listBox1.Items.Add("There are " + counto.ToString().Trim() + " o's in the sentence");
            listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's in the sentence");
            listBox1.Font = new Font("Arial", 11, FontStyle.Bold);
            listBox1.ForeColor = Color.DarkViolet;

            listBox1.Items.Add("All in all there are " + j.ToString().Trim() + " vowels in the sentence");
            listBox1.ForeColor = Color.DeepSkyBlue;
        }       

        private void btnClear_Click(object sender, EventArgs e)
        {

            textBox1.Text = null;
            listBox1.Items.Clear();
        }

Recommended Answers

All 11 Replies

You can do it with the KeyPress or KeyDown event for the text box. Both of those have event args that tell you what key was pressed.

Hi Tom Gunn
Thanks for the short reply.

I've tried the KeyDown Event for the textbox. But everytime I'll write a sentence, it will repeat the counted vowels all the time.
I would like that if I type a sentence for example:
"these are vowels" will display = there are 6 vowels in the sentence.
That means everytime I type, the counter change like from 1,2,3,4,5,6 in the same line.
I'm not sure where my mistakes here in my code:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            string yourSentence;
            yourSentence = textBox1.Text.ToLower().Trim();

            int counta = 0;
            int counte = 0;
            int counti = 0;
            int counto = 0;
            int countu = 0;

            int j = counta + counte + counti + counto + countu;


            foreach (char v in yourSentence)
            {
                switch (v)
                {
                    case 'a':
                        j++;
                        break;


                    case 'e':
                        j++;
                        break;

                    case 'i':
                        j++;
                        break;

                    case 'o':
                        j++;
                        break;

                    case 'u':
                        j++;
                        break;
                }
            }

         listBox1.Items.Add("All in all there are " + j.ToString().Trim() + " vowels in the sentence");
            listBox1.ForeColor = Color.DeepSkyBlue;

The event is fired for each character. You do not need to loop over everything that has already been tested in the text box. Test just that one character and add to a count field:

public class Form1
{
    private int _vowels = 0;

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // you write IsVowel()
        if (IsVowel(e.KeyData)) ++_vowels;
        else
        {
            // handle backspacing and deleting if you want
        }

        labelCount.Text = _vowels.ToString();
    }
}

The event is fired for each character. You do not need to loop over everything that has already been tested in the text box. Test just that one character and add to a count field:

public class Form1
{
    private int _vowels = 0;

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // you write IsVowel()
        if (IsVowel(e.KeyData)) ++_vowels;
        else
        {
            // handle backspacing and deleting if you want
        }

        labelCount.Text = _vowels.ToString();
    }
}

Ok I'll try this Tom. But that means I still have to retain my original code where I have it under:
private void btnCount_Click(object sender, EventArgs e)
is that right?

Btw, if I write the private int _vowels = 0; I got an error saying that expected token. What does it mean?

Thanks

But that means I still have to retain my original code where I have it under:
private void btnCount_Click(object sender, EventArgs e)
is that right?

If you still want to have the same behavior on a button click that you do now, yes. But keeping a running count means you do not need to have a separate button that counts all vowels from scratch.

Btw, if I write the private int _vowels = 0; I got an error saying that expected token. What does it mean?

You may be adding it to the wrong place. _vowels is a field for your form class, not a local variable. The code I gave has it in the right place. Make sure that you do the same thing and it should work.

Hi Tom: this is what I did now:

private void btnCount_Click(object sender, EventArgs e)
{
string yourSentence;
yourSentence = textBox1.Text.ToLower().Trim();
}

private void textBox1_KeyDown(object sender, EventArgs e)
{
   string yourSentence;
   yourSentence = textBox1.Text.ToLower().Trim();
   
char ch1 = 'a';
char ch2 = 'e';
char ch3 = 'i';
char ch4 = 'o';
char ch5 = 'u';

int counta = 0;
int counte = 0;
int counti = 0;
int counto = 0;
int countu = 0;

int j = counta + counte + counti + counto + countu;

foreach (char v in yourSentence)
{
if (v == ch1) { counta++; j++; }

else if (v == ch2) { counte++; j++; }

else if (v == ch3) { counti++; j++; }

else if (v == ch4) { counto++; j++; }

else if (v == ch5) { countu++; j++; }
}



   if (btnCount_Click(e.KeyData)) ++j;

listBox1.Items.Add("There are " + counta.ToString().Trim() + " a's in the sentence");
listBox1.Items.Add("There are " + counte.ToString().Trim() + " e's in the sentence");
listBox1.Items.Add("There are " + counti.ToString().Trim() + " i's in the sentence");
listBox1.Items.Add("There are " + counto.ToString().Trim() + " o's in the sentence");
listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's in the sentence");
listBox1.Items.Add("All in all there are " + j.ToString().Trim() + " vowels in the sentence");
}

You are kind of missing the point of the KeyDown event. It gets fired when a new character is added to the text box, and only that new character needs to be checked for a vowel. With a label holding the running total and being updated each time the event is fired, there is no need for a button. Here is a simple form that shows what I mean:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Daniweb
{
	class MainForm: Form
	{
		#region Form Controls
		private TextBox _sentence;
		private Label _vowelCount;
		#endregion

		private int _vowels = 0;

		public MainForm()
		{
			SuspendLayout();

			_vowelCount = new Label();
			_vowelCount.Dock = DockStyle.Top;
			UpdateCount();
			Controls.Add(_vowelCount);

			_sentence = new TextBox();
			_sentence.Dock = DockStyle.Top;
			_sentence.KeyDown += _sentence_KeyDown;
			Controls.Add(_sentence);

			ResumeLayout();
		}

		void _sentence_KeyDown(object sender, KeyEventArgs e)
		{
			if (IsVowel(e.KeyData)) ++_vowels;
			else
			{
				// handle backspacing and deleting if you want
			}

			UpdateCount();
		}

		private bool IsVowel(Keys key)
		{
			return key == Keys.A ||
			       key == Keys.E ||
			       key == Keys.I ||
			       key == Keys.O ||
			       key == Keys.U;
		}

		private void UpdateCount()
		{
			_vowelCount.Text = "There are " + _vowels + " vowels.";
		}
	}
}

Hi Tom

I'll re work my code and will let you know for the result
Thank

Hi Tom this is what I've got now. And it works fine. Thanks. I have one question in your code. This part I don't understand: Is it the same with instance variables? What is the function?


#region Form Controls
private TextBox _sentence;
private Label _vowelCount;
#endregion

using System;  
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms; 
      namespace Daniweb
      { 
      class MainForm: Form
        {   
         //#region Form Controls
        //private TextBox _sentence;  
        //private Label _vowelCount;
        //#endregion
      
          private int  totalVowels = 0;

    public MainForm()
      {
            InitializeComponent();
      }
      
    
     private void textBox1_KeyDown(object sender, KeyEventArgs e)
     {
        if (IsVowel(e.KeyData)) ++totalVowels;   
      
        else
        {
           // handle backspacing and deleting if you want
        }  
      
             UpdateCount();
      }

       
private bool IsVowel(Keys key)
     {
      return key == Keys.A ||
      key == Keys.E ||
      key == Keys.I ||
      key == Keys.O ||
      key == Keys.U;
      }

      private void UpdateCount()
      {
         textBox2.Text = "There are " + totalVowels + " vowels.";
      }
      }
      }

Thanks

You have textBox1 and textBox2. From the names I guess you dragged and dropped using the visual designer. What that does is generate a partial class for you with all of the dirty work of creating and placing controls. You can look at that code by finding the <filename>.Designer.cs file in your project that corresponds to the <filename>.cs file.

All of that extra fluff takes space and adds complexity, so I did it manually by creating controls and putting them directly into the form class without using a partial class. My _sentence and _vowelCount are the same as your textBox1 and textBox2.

I see, thanks Tom for the input.
This is considered solved now.
Cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.