Search code examples
xamarinxamarin.formsxamarin.androidxamarin.iosxamarin-studio

How to get selected item in Xamarin


I have a Picker in Xamarin and I want to pass the selected item in Picker to the another page(TablePage). Below this Picker there is a button and whenever it is clicked I want to go to the other page and display the selected value in the pther page.

<Picker x:Name="SelectTablePicker" Title="Select table" TextColor="#676FA3" TitleColor="#676FA3" FontSize="Title" ItemsSource="{Binding TablesFromViewModelCollector}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedTable}" />
<Button x:Name="SelectTableButton" Text="Select Table" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}" Clicked="Selected_Button" />

So how I am trying to pass this value is with click event:

async void Selected_Button(object sender, System.EventArgs e)
        {
            var SelectTablePicker = (Picker)sender;
            int selectedIndex = SelectTablePicker.SelectedIndex;

            if (selectedIndex != -1)
            {
                await Navigation.PushAsync(new TablePage((string)SelectTablePicker.ItemsSource[selectedIndex]));
            }
            
        }

And on the Table Page, I created Label where I want to show the selected item:

<Label x:Name="MyLabel" Text="#" HorizontalOptions="Fill"  Grid.Column="0" BackgroundColor="#FF5959" TextColor="#EEF2FF" HorizontalTextAlignment="Left" Padding="0, 0, 0, 10" VerticalTextAlignment="Center"/>

And here its controller:

public TablePage(string tableName)
        {
            InitializeComponent();

            MyLabel.Text = $"{UserName}";
        }

But whenever I click the button I am getting an error and I couldnt figure out why.


Solution

  • this is a button click event, so the sender is a Button, not a Picker

    var SelectTablePicker = (Picker)sender;
    int selectedIndex = SelectTablePicker.SelectedIndex;
    

    instead just do this

    // SelectTablePicker is the name of your picker
    int selectedIndex = SelectTablePicker.SelectedIndex;
    

    and even better, you are already binding SelectedItem="{Binding SelectedTable}" so you could just get the value of SelectedTable directly from your VM

    finally, you want to cast the selected item as a Table, not a string

    new TablePage((Table)SelectTablePicker.ItemsSource[selectedIndex])