Vasco Alves
Vasco Alves

Reputation: 29

How to add value to array from textBox? WinForms C#

I want to add values to an array. These values come from textBoxes. When I click the button "Calcular", it should show every number but that doesn't happen.

Can anyone explain me what's happening?

Code:

//Declaração das Variáveis/Arrays
float[] Valores = new float[5];
int Limite = 0;
float Valor0, Valor1, Valor2, Valor3, Valor4;

//Introduzir Valores
private void TextBoxIntroduzirValores_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (Limite >= 5)
        {
            MessageBox.Show("Só pode introduzir 5 números!");
            TextBoxIntroduzirValores.Text = "";
        }
        else
        {
            for (int i = 0; i < 4; i++)
            {
                float ValorTemp = Convert.ToSingle(
                    TextBoxIntroduzirValores.Text);
                Valores[i] = ValorTemp;
            }

            ListaValores.Items.Add(TextBoxIntroduzirValores.Text);
            TextBoxIntroduzirValores.Text = "";
            Limite = Limite + 1;
        }
    }
}

//Introduzir Valores
private void TextBoxIntroduzirValores_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(
        TextBoxIntroduzirValores.Text, "[^0-9]"))
    {
        MessageBox.Show("Introduza apenas números por favor!");
        TextBoxIntroduzirValores.Text = TextBoxIntroduzirValores.Text.Remove(
            TextBoxIntroduzirValores.Text.Length - 1);
    }
}

//Botão Calcular
private void Calcular_Click(object sender, EventArgs e)
{
    Valor0 = Valores[0];
    Valor1 = Valores[1];
    Valor2 = Valores[2];
    Valor3 = Valores[3];
    Valor4 = Valores[4];
    string Valor00 = Convert.ToString(Valor0);
    string Valor11 = Convert.ToString(Valor1);
    string Valor22 = Convert.ToString(Valor2);
    string Valor33 = Convert.ToString(Valor3);
    string Valor44 = Convert.ToString(Valor4);
    TextBoxMaximo.Text = Valor00 + Valor11 + Valor22 + Valor33 + Valor44;
}

WinForm in Design View:

enter image description here

And at runtime:

enter image description here

As you can see, it's not showing the array correctly

Upvotes: 1

Views: 1914

Answers (2)

Rufus L
Rufus L

Reputation: 37020

I see a couple of things you might want to change in your code.

When you're adding an item to the ListBox:

  1. You should use the Length property of the array you're populating as the condition. This reduces the number of places you have to update your code if you decide later to change the max number of values.

  2. You are currently using a loop to add the same number to the array to the first four indexes. Instead, you can just use the Limite as the index to add the item to.

So the method would look like:

private void TextBoxIntroduzirValores_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (Limite >= Valores.Length)
        {
            MessageBox.Show($"You can only enter {Valores.Length} numbers!");
            TextBoxIntroduzirValores.Text = "";
        }
        else
        {
            // Add item to array
            Valores[Limite] = Convert.ToSingle(TextBoxIntroduzirValores.Text);

            // Increment index
            Limite = Limite + 1;

            // Add item to listbox
            ListaValores.Items.Add(TextBoxIntroduzirValores.Text);

            // Clear textbox
            TextBoxIntroduzirValores.Text = "";
        }
    }
}

Also, when you're calculating the results, you can either use the System.Linq extension methods on the array that's storing the values:

private void Calcular_Click(object sender, EventArgs e)
{
    // You can calculate values using Sytem.Linq extension methods
    txtMin.Text = Valores.Min().ToString();
    txtMax.Text = Valores.Max().ToString();
    txtAvg.Text = Valores.Average().ToString();
    txtTotal.Text = Valores.Sum().ToString();
}

Or, you can calculate these values the long way. To do this, create variables with some default values. For the default Min value, we use the largest number possible. Then, when we loop through each item in the array, we see if the item is less than Min, and if it is, update Min with this new value. Similarly, we use the smallest number possible as the default value for Max. This ensures that these items are accurate at the end of the loop.

For Total, we start the value at 0 and then each item in the array to the Total as we loop through it. And for Average, we just divide the Total by the number of items in the array (which is the Length property):

private void Calcular_Click(object sender, EventArgs e)
{
    // Or you can do it the long way. First start with default values:
    float min = Single.MaxValue;
    float max = Single.MinValue;
    float total = 0;

    // Then go through each item in the array 
    // and update the values above if necessary
    foreach (float item in Valores)
    {
        if (item < min) min = item;
        if (item > max) max = item;
        total = total + item;
    }

    // Calculate average last since we need the total first
    float avg = total / Valores.Length;

    // Update the textboxes with these values:
    txtMin.Text = min.ToString();
    txtMax.Text = max.ToString();
    txtAvg.Text = avg.ToString();
    txtTotal.Text = total.ToString();
}

Upvotes: 1

Riccardo Raffini
Riccardo Raffini

Reputation: 396

I do not know if I really understand what you want, anyway ...

Variables:

float[] values = new float[5];
int num = 0;

assuming that you enter your 5 values ​​from a textbox tbValues

private void tbValues_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter && num < 5 && !(string.IsNullorEmpty(tbValues.text)))
    {
         values[num] = int.Parse(tbValues.Text);
         listValues.Items.Add(values[num].ToString());
         num ++;
    }
    else
         ...
    tbValues.Clear();
}

Then in buttun Calc btnCalc

private void btnCalc_Click(object sender, EventArgs e)
{
    tbMax.Text = values.Max().ToString();
    tbMin.Text = values.Min().ToString();
    float sum = values.Sum();
    tbSum.Text = sum.Tosting();
    float average = sum / values.Length;
    tbAverage.Text = average.ToString();
}

Upvotes: 0

Related Questions