名称''枚举器'在当前上下文中不存在

时间:2013-01-13 10:59:59

标签: c#

使用System; 使用System.Data; 使用System.Windows.Forms; 使用System.Data.SqlClient; 使用System.Linq;

namespace ProiectBDD
{
    public partial class AdaugaIntrebari : UserControl
    {
        private string connstring;

        public string Connstring
        {
            get { return connstring; }
            set { connstring = value; }
        }

        public AdaugaIntrebari(string p_connstring)
        {
            connstring = p_connstring;
            InitializeComponent();
            IncarcaCategorii();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (enumerator.MoveNext())
            {
                label1.Text = enumerator.Current.Categorie;
            }
        }

        public void IncarcaCategorii()
        {
            DataClasses1DataContext dc = new DataClasses1DataContext();
            var q = from a in dc.GetTable<Categorii>()
                    select a;
            var enumerator = q.AsEnumerable().GetEnumerator();
        }
    }
}

我得到名称enumerator在我的按钮事件处理程序中的当前上下文错误中不存在 方法。

3 个答案:

答案 0 :(得分:1)

button1_Click不了解enumerator,因为它仅存在于IncarcaCategorii中 你需要把它变成一个类字段

using System;
using System.Data;
using System.Windows.Forms;
using System.Linq;

namespace ProiectBDD
{
    public partial class AdaugaIntrebari : UserControl
    {
        private string connstring;
        private IEnumerator<DataRow> _enumerator;

        public string Connstring
        {
            get { return connstring; }
            set { connstring = value; }
        }

        public AdaugaIntrebari(string p_connstring)
        {
            connstring = p_connstring;
            InitializeComponent();
            IncarcaCategorii();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_enumerator == null) return;

            if (enumerator.MoveNext())
            {
                label1.Text = _enumerator.Current.Categorie;
            }
        }

        public void IncarcaCategorii()
        {
            DataClasses1DataContext dc = new DataClasses1DataContext();
            var q = from a in dc.GetTable<Categorii>()
                    select a;
            _enumerator = q.AsEnumerable().GetEnumerator();

        }
    }
}

答案 1 :(得分:0)

enomerator变量在范围

中不存在

请参阅此方法:

public void IncarcaCategorii()
{
    DataClasses1DataContext dc = new DataClasses1DataContext();
    var q = from a in dc.GetTable<Categorii>()
            select a;
    var enumerator = q.AsEnumerable().GetEnumerator();
} // This is where "enumerator" become subject to garbage collection

enumerator变量需要以某种方式传递到这里:

private void button1_Click(object sender, EventArgs e)
{
    if (enumerator.MoveNext())
    {
        label1.Text = enumerator.Current.Categorie;
    }
}

答案 2 :(得分:0)

label1.Text = enumerator.Current.Categorie.[FieldName];

或者您IEnumerator的当前位置可能已脱离上下文,再次选择对象