1

I have been trying to make a program in which, I add data of numbers but in texts, that these are added to a listbox and later make the sum of said values, only that they have explained to me that once the data has been added, now I must do a for loop to go through each data of the first array and thus be able to convert each one of them to a numeric value. Only when doing the conversion on the add button, it tells me that it is not in the correct format.

I declared the array in the public partial class like this: string [] array;

private void bt_capturar_Click(object sender, EventArgs e)
{
    string datos = txb_numeros.Text;
    arreglo = datos.Split(',');
    lbx_elementos.Items.Clear();
    foreach (string elementos in arreglo)
    {
        lbx_elementos.Items.Add(elementos);
    }
}

private void bt_sumar_Click(object sender, EventArgs e)
{
    int suma = 0;
    for (int x = 0; x < arreglo.Length; x++)
    {
        int numero;
        numero = int.Parse(arreglo[x]);
        suma = suma + numero;
    }

    MessageBox.Show("La suma es igual a " + suma.ToString());
}
1
  • I assume you mean string[] arreglo not string[] array? What exactly goes wrong? int.Parse might crash when the string isn't a proper integer (like "string" or even "13.2"). Commented Jun 8, 2021 at 20:15

4 Answers 4

2

Often we query array with a help of Linq (note, that we use int.TryParse since some items can not represent any integer value)

  using System.Linq;

  ...

  private void bt_sumar_Click(object sender, EventArgs e)
  {
      int suma = arreglo.Sum(item => int.TryParse(item, out int v) ? v : 0);

      MessageBox.Show($"La suma es igual a {suma}"); 
  }

However, you can implement a simple loop:

  private void bt_sumar_Click(object sender, EventArgs e)
  {
      int suma = 0;

      foreach (string item in arreglo)
          suma += int.TryParse(item, out int v) ? v : 0;

      MessageBox.Show($"La suma es igual a {suma}");             
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Use Int32.TryParse instead

int numero;
bool success = Int32.TryParse(arreglo[x], out numero);
suma += success ? numero : 0;

Comments

1

If I understand correctly, you want to already validate the input or convert it in bt_capturar_Click?

In that case you can do the following:

    private void bt_capturar_Click(object sender, EventArgs e)
    {
        string datos = txb_numeros.Text;
        arreglo = datos
          .Split(',')
          .Select(Int32.Parse)
          .ToArray();

        // Or ignore invalid values:
        //arreglo = datos
        //  .Split(',')
        //  .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)
        //  .Where(n => n != null)
        //  .ToArray();
        
        lbx_elementos.Items.Clear();
        foreach (string elementos in arreglo)
        {
            lbx_elementos.Items.Add(elementos.ToString()); // Maybe use AddRange?
        }

    }

    private void bt_sumar_Click(object sender, EventArgs e)
    {
        MessageBox.Show("La suma es igual a " + arreglo.Sum());
    }
}

Comments

0

Using the following simple code, you will resolve your problem easily.

string strInput = "1,2,3,4,5";
string[] arrInput = strInput.Split(',');

// convert a string array to an int array
int[] arrResult = Array.ConvertAll(arrInput, s => int.TryParse(s, out int t) ? t : 0);

// sum up an array of integers
int nSum = arrResult.Sum();

References: Array.ConvertAll, int.TryParse, Enumerable.Sum

Comments