Search code examples
c#stringfloating-pointcounterwindows-forms-designer

Windows Form App Float to String


Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.

    private static string _globalVar = "n";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
    public Form1()
    {
        InitializeComponent();
        button1.Text = "Enter";
    }
    string LNum { get; set; }
    public void button1_Click_1(object sender, EventArgs e)
    {
        MessageBox.Show(LNum);
    }

    public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        float n = 0;

        if (Control.ModifierKeys == Keys.Space)
        {   
            n = n + 1; ;
        }
        string.Format("{0:N1}", n);
        string LNum = Convert.ToString(n);

    }

Solution

  • What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.

    Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.

        public void button1_Click(object sender, EventArgs e)
        {
            int n = 0;
            for (int counter = 0; counter < richTextBox1.TextLength; counter++)
            {
                if (richTextBox1.Text[counter] == ' ')
                {
                    n++;
                }
            }
    
            MessageBox.Show(n.ToString("N1"));
        }
    

    The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.

    In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.

    The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).