Mary
Mary

Reputation: 161

Combobox Examples

I am getting the following error for foreach

Foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

I am making any syntax error

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Namepopu_SelectedIndexChanged(object sender, EventArgs e)
        {
            // this.textBox1.Text = Namepopu.Text;
           // this.textBox1.Text = " ";

            foreach (int i in Namepopu.SelectedItem)
                this.textBox1.Text += Namepopu.Text[i];
            {

            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

Upvotes: 1

Views: 1314

Answers (4)

Sean Hunter
Sean Hunter

Reputation: 1051

The problem is that you are trying to get the enumerator for something that does not implement the IEnumerator interface. For a listing of the collection types you can iterate using a for each this MSDN article is useful (http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx).

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

textBox1.Text = string.Empty;
foreach (var item in Namepopu.SelectedItems)
   textBox1.Text += item.ToString();

Upvotes: 0

Tom Vervoort
Tom Vervoort

Reputation: 5108

What's the contents of Namepopu.SelectedItem ? An array ? A generic list ? Cast it to it's original type first, then iterate over it in your foreach.

For example:

List<int> myValues = (List<int>)Namepopu.SelectedItem;

foreach (int i in myValues)
{
  ...
}

or

int[] myValues = (int[])Namepopu.SelectedItem;

foreach (int i in myValues)
{
  ...
}

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128307

Perhaps you meant to do this?

for (int i = 0; i < Namepopu.Items.Count; ++i)
{
    this.textBox1.Text += Namepopu.Items[i].ToString();
}

Upvotes: 5

Related Questions