Home > Net >  foreach can't operate on variables of type 'object' because 'object' doesn&
foreach can't operate on variables of type 'object' because 'object' doesn&

Time:03-15

private void pckItemCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            var picker = (Picker)sender;
            int selectedIndex = picker.SelectedIndex;

            if (selectedIndex != -1)
            {

                var field = picker.ItemsSource[selectedIndex];

                foreach (var data2 in field)
                {

                }
            }
        }

I Want to get data from ItemSource, when i looping data from var field, i get an error .. what should i do ?

CodePudding user response:

private void pckItemCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            var picker = (Picker)sender;
            int selectedIndex = picker.SelectedIndex;

            if (selectedIndex != -1)
            {
                var field = picker.ItemsSource[selectedIndex];

                foreach (var propertyInfo in field.GetType().GetProperties())
                {
                        string test = propertyInfo.GetValue(field).ToString();
                        string test2 = propertyInfo.Name;
                }
            }
        }

Finally i am found this answer, i want to get property value from object and i get it.. thanks to everyone who helped answer my question

CodePudding user response:

Do you want to access the property of the selected object, right?

Then, you can get the selected object by the selectedIndex just as your code, and we can access the properties of the selected object by casting the object into the type of the item of the Picker.

Please refer to the following code:

    private void Picker_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        var picker = (Picker)sender;
        int selectedIndex = picker.SelectedIndex;

        if (selectedIndex != -1)
        {
            // here you can cast the field to your type,mine is `Monkey `
            Monkey field = (Monkey)picker.ItemsSource[selectedIndex];

            System.Diagnostics.Debug.WriteLine("--------> "  selectedIndex "<---->"   field.Name);

        }
    }

Note:

Since the field is not a list, so we cann't iterate over field

foreach (var data2 in field) // Code usage error
            {

            }
  • Related