如何使用字符串列表作为列表框的数据源
这是我编写的代码,它通常可以工作,但有时会失败(或多或少有四分之一):
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
string codbultocomp = null;
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT codbultocomp FROM envios WHERE codigodestino=@codigodestino AND estado=@pendiente", con))
{
cmd.Parameters.AddWithValue("@codigodestino", codigoDestino);
cmd.Parameters.AddWithValue("@pendiente", "pendiente");
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
codbultocomp = reader["codbultocomp"].ToString();
_items.Add(codbultocomp);
}
reader.Close();
}
listBox1.DataSource = _items;
}
当它失败时,应用程序会冻结,如果我暂停调试,它会在最后一个大括号中停止。我尝试使用 try/catch 块显示错误,但它没有显示任何内容并停在同一个地方。我还尝试观察列表框数据源在“观察”列表中显示此错误:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
知道我做错了什么吗?
Here is the code I made, it usually works, but sometimes fails (1 out of 4 times more or less):
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
string codbultocomp = null;
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT codbultocomp FROM envios WHERE codigodestino=@codigodestino AND estado=@pendiente", con))
{
cmd.Parameters.AddWithValue("@codigodestino", codigoDestino);
cmd.Parameters.AddWithValue("@pendiente", "pendiente");
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
codbultocomp = reader["codbultocomp"].ToString();
_items.Add(codbultocomp);
}
reader.Close();
}
listBox1.DataSource = _items;
}
When it fails the application freezes, and if I pause the debug it is stopped in the last brace. I tried to show an error using a try/catch block but it didn't show anything and stopped in the same place. I also tried to watch the listbox datasource shows this error in the "watch" list:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
Any idea of what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
using
之后调用它,所有 IDisposable 对象都将在using
之后被释放。Call it after your
using
, all IDisposable objects will be disposed afterusing
.为什么不尝试这样的事情:
为了清晰的代码,创建一个类似的方法:
然后使用:
Why don't you try something like this:
For a clear code create a method like:
and then just use:
您只需关闭 con 对象即可。也无需关闭阅读器。 con 对象的使用要小心。不需要休息。
You just close the con object. No need to close the reader as well. The using of con object takes care. Rest using isnt required.