使用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
在我的按钮事件处理程序中的当前上下文错误中不存在
方法。
答案 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
的当前位置可能已脱离上下文,再次选择对象