How to use values of each entry in Xamarin?

1

The code at the moment is like this, I'm doing the whole visual part in the same code behind, without implementing anything directly in XAML. I create the number of entries according to the value entered in an Entry called: sample. As I'm starting in Xamarin / C #, I do not know how to use the value of each entry (generated dynamically) to do the calculation, does anyone have any idea what I should do? The code looks like this:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Leitura : ContentPage
{
    Calculo calculo = new Calculo();

    public Action<object, EventArgs> Clicked { get; }

    public Leitura()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        Entry amostra = new Entry()
        {
            Placeholder = "Quantidade de amostras",
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Start,
            Keyboard = Keyboard.Numeric,
            HeightRequest = 40,
            WidthRequest = 230,
        };

        var layout = new StackLayout();

        Label label = new Label()
        {
            Text = "Amostras",
        };
        layout.Children.Add(label);
        layout.Children.Add(amostra);

        Content = layout;

        amostra.Completed += Amostra_Completed;



        void Amostra_Completed(object sender, EventArgs e)
        {

            amostra.IsEnabled = false;

            calculo.Qnt_amostra = Convert.ToDouble(amostra.Text);
            if (calculo.Qnt_amostra > 100)
            {
                DisplayAlert("Valor Inválido!", "Insira no máximo 100 amostras.", "Ok");
                amostra.IsEnabled = true;
            }
            else
            {
                if (calculo.Qnt_amostra < 0)
                {
                    DisplayAlert("Valor Inválido!", "Valor não pode ser negativo. ", "Ok");
                    amostra.IsEnabled = true;
                }
                else
                {


                    for (int i = 0; i < (int)calculo.Qnt_amostra; i++)
                    {   
                       //gostaria de utilizar este valor destas entries,(geradas dinamicamente de acordo com a entrada do usuario),para realizar o calculo
                        var entInput = new Entry();
                        entInput.IsEnabled = true;
                        entInput.Keyboard = Keyboard.Numeric;
                        entInput.Placeholder = $"Peso da {(i + 1)}º amostra";

                        entInput.WidthRequest = 200;
                        calculo.Peso = entInput.Text;
                        layout.Children.Add(entInput);
                    }

                    Button botao = new Button
                    {
                        Text = "Calcular",
                        TextColor = Color.White,
                        BackgroundColor = Color.Green,
                        WidthRequest = 130,
                        HeightRequest = 40,
                        CornerRadius = 5,

                    };
                    botao.Clicked += Botao;

                    layout.Children.Add(botao);

                    ScrollView scroll = new ScrollView()
                    {
                        Content = layout
                    };
                    Content = scroll;


                }
            }
        }


    }

    protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var acao = await DisplayAlert("Atenção!", "Todos as medidas serão perdidas! Deseja Contiunar?", "Sim", "Cancelar");
            if (acao) await Navigation.PopAsync();
        });
        return true;
    }

    public void Botao(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Resultado(calculo));
    }

}
    
asked by anonymous 06.07.2018 / 19:04

2 answers

0

To get the value of each entry, I used a new StackLayout ONLY for the entries, so I used the OnButtonClicked event for any button, and clicking the button returns it to me. The process can be done without the use of the button, it was just a preference of its own.

//adicionando as entradas
 for (int i = 1; i <= numero_de_entradas_desejadas ; i++)
 // utilizei i=1 pois NÃO se trata de um VETOR, então não há diferença entre iniciar no indice 0, ou não.
        {
            var peso = new Entry();
            peso.Placeholder = $"Peso da {i}° amostra";                
            peso.Keyboard = Keyboard.Numeric;
            //entradas é o stack layout para as entradas geradas dinamicamente
            entradas.Children.Add(peso);

        }

private async void Botao(object sender, EventArgs e)
    {
        foreach (Entry entry in entradas.Children)
        {
            // var variavel_a_ser_manipulada = entry.Text;
        }

    }
    
09.07.2018 / 18:47
0
//Guarde as Entry Dentro de uma Lista
                    List<Entry>  entry = new List<Entry>();
                    entry.Add(new Entry()
                    {
                        Text = "Calcular",
                        TextColor = Color.White,
                        BackgroundColor = Color.Green,
                        WidthRequest = 130,
                        HeightRequest = 40,
                        CornerRadius = 5,

                    });

.

    ObterValores(entry);


    private List<string> ObterValores(List<Entry> entry)
    {
        List<string> ValoresDeCadaEntry = new List<string>();
        foreach (var item in entry)
        {
            //Para cada Entry Obtemos o valor do texto
            ValoresDeCadaEntry.Add(item.Text);
            //Adicionamos os valores de Cada Entry a esta Lista
        }
       return ValoresDeCadaEntry;
    }


        string texto;
        foreach (var item in ObterValores(entry))
        {
            texto += item + Environment.NewLine
        }

////Aqui esta o texto 

Or you can convert this to int and compute with each element of a list of type int

    
06.07.2018 / 19:16