简体   繁体   English

如何从textBox向数组添加值? WinForms C#

[英]How to add value to array from textBox? WinForms C#

I want to add values to an array. 我想将值添加到数组。 These values come from textBoxes. 这些值来自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: 在设计视图中的WinForm:

在此处输入图片说明

And at runtime: 在运行时:

在此处输入图片说明

As you can see, it's not showing the array correctly 如您所见,它没有正确显示数组

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 假设您从文本框tbValues输入5个值

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 然后在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();
}

I see a couple of things you might want to change in your code. 我看到您可能需要在代码中更改的几件事。

When you're adding an item to the ListBox : 将项目添加到ListBox

  1. You should use the Length property of the array you're populating as the condition. 您应该使用要填充的数组的Length属性作为条件。 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. 相反,您可以仅使用Limite作为将项目添加到的索引。

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: 同样,在计算结果时,可以在存储值的数组上使用System.Linq扩展方法:

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. 对于默认的Min ,我们使用可能的最大值。 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. 然后,当我们遍历数组中的每个项目时,我们将查看该项目是否小于Min ,如果是,则使用此新值更新Min Similarly, we use the smallest number possible as the default value for Max . 同样,我们使用尽可能小的数字作为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. 对于Total ,我们将值从0开始,然后遍历该数组时将数组中的每个项目设置为Total And for Average , we just divide the Total by the number of items in the array (which is the Length property): 对于Average ,我们只将Total除以数组中的项目数(这是Length属性):

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM