How to find out which row is clicked or selected in ListView Xamarin Form

I am new to Xamarin. I have a question about ListView in Xamarin form. How to find out which row or index every time I enter (or select) in a listView? Below is the code I tried, but e.SelectedItem shows nothing. Thanks for the help.

listView.ItemSelected += async (sender, e) => {

    if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row

    await DisplayAlert("Tapped", e.SelectedItem + " row was selected", "OK");

    ((ListView)sender).SelectedItem = null; // de-select the row
};
+4
source share
3 answers

I have a list view, and when I click, I need to go to the details page. Below is the code I use for it.

listView.ItemSelected += async (sender, e) =>
            {
                if (e.SelectedItem == null)
                {
                    // don't do anything if we just de-selected the row
                    return;
                }
                else
                {
                    Resource resource = e.SelectedItem as Resource;
                    listView.SelectedItem = null;
                    await Navigation.PushAsync(new ResourceDetails(resource));
                }
            };

In your case, I would modify the code as follows:

listView.ItemSelected += async (sender, e) => {

    if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row

    await DisplayAlert("Tapped", (e.SelectedItem as YourDataType).Name + " row was selected", "OK");

    ((ListView)sender).SelectedItem = null; // de-select the row
};
+6
source

I found a solution how to find the row index. :)

listView.ItemSelected += async (sender, e) => {
                if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row
                Person person = (Person)e.SelectedItem;
                int index = -1;

                for(int i = 0; i < people.Count; i++)
                {
                    if(people[i] == person)
                    {
                        index = i;
                        break;
                    }
                }

                await DisplayAlert("Tapped", person.Name + " row was selected " + index.ToString(), "OK");

                ((ListView)sender).SelectedItem = null; // de-select the row
            };
0
source

IndexOf ItemSource - ""

int index = people.IndexOf(person);

for

0
source

All Articles