How to use values from each entry in Xamarin?

Asked

Viewed 247 times

1

The code at the moment is like this, I am doing all the visual part in the Behind code even, 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 don’t know how to use the value of each entry ( dynamically generated) to do the calculation, does anyone have any idea what I should do? The code is 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));
    }

}

2 answers

0


In order to get the value of each entry, I selected a new Stacklayout ONLY for the Ntries, so I used the Onbuttonclicked event for any button, and when clicking the button it returns the desired one. The process can be done without the use of the boot, it was only 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;
        }

    }

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 calculate with each element of an int-type list

  • got it, but how would I display this list of Ntries on the screen? since I’m using a stack layout

  • You can put it in a string

  • @Leonardoosvalddesouza how about so?

  • but how would I use the values? because first the user needs to inform them in the Ntries

Browser other questions tagged

You are not signed in. Login or sign up in order to post.