0

I've been learning C# and trying to create a little bank system with deposit, withdraw and create account options. But I'm having trouble when I try to create one more account than the default (that should be increased everytime I create a new account). I've been getting this: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" even in lines where there's no array. Can you help me? Here are all the codes you may need:

Edit: I think I got what's my problem with the array from comments but WHY the array size isn't increasing with maximocontas, once it should be increased by one after one account get created. So I'll if the limit is 1,I create one account then the limit now should be 2 because of maximocontas ++; and contas[maximocontas];, shouldn't it?

My problem is on AbreConta() Form1.cs (Where the function with my problem is)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Banco
{
    public partial class Form1 : Form
    {
        private int maximocontas = 1; //maximo de contas
        private int contascriadas = 0;
        private Conta[] contas;// declara uma variavel tipo conta chamada contas
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.contas = new Conta[maximocontas];
        }
        public void AbreConta(Conta conta)
        {
            maximocontas++;
            this.contas[this.contascriadas] = conta;
            MessageBox.Show(Convert.ToString(contascriadas));
            contascriadas++;
            ComboContas.Items.Add("titular: " + conta.Titular.Nome);
            DestinoTransfBox.Items.Add("titular:" + conta.Titular.Nome);
        }
        private void BotaoDeposito_Click(object sender, EventArgs e)
        {
            string valorDigitado = TextoValor.Text;
            double valorOperavel = Convert.ToDouble(valorDigitado);
            int busca = ComboContas.SelectedIndex;
            Conta selecionada = contas[busca];
            if (valorOperavel > 0)
            {
                double valor;
                valor = Convert.ToDouble(TextoValor.Text);
                selecionada.Deposita(valor);
                TextoSaldo.Text = Convert.ToString(selecionada.Saldo);
            }
            else
            {
                MessageBox.Show("Valor não depositavel");
            }
        }

        private void BotaoSaque_Click(object sender, EventArgs e)
        {
            string valorDigitado = TextoValor.Text;
            double valorOperavel = Convert.ToDouble(valorDigitado);
            int busca = ComboContas.SelectedIndex;
            Conta selecionada = this.contas[busca];
            if (selecionada.Saldo >= valorOperavel)
            {
                double valor;
                valor = Convert.ToDouble(TextoValor.Text);
                selecionada.Saque(valor);
                TextoSaldo.Text = Convert.ToString(selecionada.Saldo);
            }
            else
            {
                MessageBox.Show("Saldo Indisponivel");
            }
        }

        private void BotaoBuscar_Click(object sender, EventArgs e)
        {
            if(ComboContas.SelectedIndex <= maximocontas-1)
            {
                int busca = ComboContas.SelectedIndex;
                Conta selecionada = this.contas[busca];
                TextoNumero.Text = Convert.ToString(selecionada.Numero);
                TextoSaldo.Text = Convert.ToString(selecionada.Saldo);
                TextoTitular.Text = selecionada.Titular.Nome;
            }
            else
            {
                MessageBox.Show("Essa conta não existe!");
            }
        }

        private void ComboContas_SelectedIndexChanged(object sender, EventArgs e)
        {
            int busca = ComboContas.SelectedIndex;
            Conta selecionada = contas[busca];
            TextoTitular.Text = selecionada.Titular.Nome;
            TextoSaldo.Text = Convert.ToString(selecionada.Saldo);
            TextoNumero.Text = Convert.ToString(selecionada.Numero);
        }

        private void DestinoTransfBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int busca = DestinoTransfBox.SelectedIndex;
            Conta selecionada = contas[busca];
        }

        private void BotaoTransferir_Click(object sender, EventArgs e)
        {
            int busca = ComboContas.SelectedIndex;
            int dest = DestinoTransfBox.SelectedIndex;
            Conta destino = contas[dest];
            Conta selecionada = contas[busca];
            double valor = Convert.ToDouble(ValorTransferencia.Text);
            if(selecionada.Saldo >= valor)
            {
                Conta.Transferir(valor, selecionada, destino);
                TextoSaldo.Text = Convert.ToString(selecionada.Saldo);
                MessageBox.Show("Operação Concluida");
            }
            else
            {
                MessageBox.Show("Saldo Insuficiente Para a Transferencia");
            }
        }

        private void BotaoNovaAcc_Click(object sender, EventArgs e)
        {
            Form2 formularioDeAbertura = new Form2(this);
            formularioDeAbertura.ShowDialog();
        }
    }
}

Form2 (Account creation form)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Banco
{
    public partial class Form2 : Form
    {
        private Form1 formPrincipal;
        public Form2(Form1 formPrincipal)
        {
            this.formPrincipal = formPrincipal;
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void BotaoCriar_Click(object sender, EventArgs e)
        {
            Conta novaConta = new ContaCorrente();
            novaConta.Titular = new Cliente(TextNovoNome.Text);
            novaConta.Numero = Convert.ToInt32(TextNovoNumero.Text);
            this.formPrincipal.AbreConta(novaConta);
        }
    }
}

Conta.cs (With all account related things)

namespace Banco
{
    public class Conta
    {
        public int Numero { get ; set; }
        public double Saldo { get; protected set; } // set/gets privados não podem ser lidas por quem esta fora nem pelos herdeiros, os protected podem ser lidos pelos herdeiros mas nao por quem esta fora
        public Cliente Titular { get; set; }
        public virtual void Deposita(double valor)
        {
            this.Saldo += valor;
        }
        public virtual void Saque(double valor)
        {
            this.Saldo -= valor;
        }
        public static void Transferir(double value, Conta origem, Conta destino)
        {
            origem.Saldo -= value;
            destino.Saldo += value;
        }
    }
    public class ContaPoupanca : Conta //lê-se CountaPoupanca herda Conta, ela herdara todos os atributos, metodos e etc da class Conta
    {
        public override void Deposita(double valor) // o override pode ser feito tanto assim
        {
            this.Saldo += valor - 0.10;
        }
        public override void Saque(double valor) //como assim
        {
            base.Saque(valor + 0.10);
        }
        //A palavra base chama o comportamento que queremos reaproveitar, chama o metodo saca e passa como parametro valor + 0.10
    }
    public class ContaCorrente : Conta
    {
        public override void Deposita(double valor)
        {
            base.Deposita(valor - 0.10);
        }
        public override void Saque(double valor)
        {
            base.Saque(valor + 0.5);
        }
    }
    public class TotalizadorDeContas
    {
        public double ValorTotal { get; private set; }
        public void Soma(Conta conta)
        {
            ValorTotal += conta.Saldo;
        }
    }
}

Cliente.cs (With Cliente [customer] class)

namespace Banco
{
    public class Cliente
    {
        private string documentos;
        public string Nome { get; set; }
        public string Documentos{ get { return this.documentos; } set { this.documentos = value; } }
        public Cliente(string nome)
        {
            this.Nome = nome;
        }
    }
}

And here you find Form1 Designer: http://pastebin.com/4L944Dxd And here you find Form2 Designer: http://pastebin.com/KYaRyeUv

  • You problem is the array where you store your accounts (contas) has space only for one element. If you don't know how many elements to store then use a more flexible data structure called `List` – Steve Jan 02 '17 at 10:46
  • I was going to answer but as it's now closed, your problem probably lies with the `SelectedIndexChanged` event. When it goes from an item selected to no item selected, the selected index becomes -1, and you use that number to index into the array, which would cause that exception. – 404 Jan 02 '17 at 10:49
  • @eurotrash that issue is covered under the "unexpected results" section of the duplicate's answer. – Scott Chamberlain Jan 03 '17 at 16:11

0 Answers0