C# 如何将字符串列表用作listbox';s数据源
以下是我编写的代码,它通常有效,但有时会失败(4次中有1次多多少少):C# 如何将字符串列表用作listbox';s数据源,c#,list,listbox,datasource,C#,List,Listbox,Datasource,以下是我编写的代码,它通常有效,但有时会失败(4次中有1次多多少少): 知道我做错了什么吗?你只需关闭con对象。也不需要关闭读卡器。con对象的使用要小心。不需要使用Rest。在使用后调用它,所有IDisposable对象将在使用后被处置 ... List<string> _items = new List<string>(); ... using (SqlCeConnection con = new SqlCeConnection(Globals.conString
知道我做错了什么吗?你只需关闭con对象。也不需要关闭读卡器。con对象的使用要小心。不需要使用Rest。在使用
后调用它,所有IDisposable对象将在使用后被处置
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
...
}
listBox1.DataSource = _items;
。。。
列表_items=新列表();
...
使用(SqlCeConnection con=newsqlceconnection(Globals.consting))
{
...
}
listBox1.DataSource=\u项;
为什么不试试这样的方法:
要获得清晰的代码,请创建如下方法:
public List<string> getItems(string codigodestino, string pendiente)
{
List<string> _items = new List<string>();
SqlCeConnection con = new SqlCeConnection(Globals.conString);
string Qyery = "SELECT codbultocomp FROM envios WHERE codigodestino='" + codigodestino + "' AND estado='" + pendiente +"'";
try
{
con.Open();
SqlCeCommand cmd = new SqlCeCommand(Qyery, con);
cmd.CommandType = CommandType.Text;
SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
_items.Add((string)reader["codbultocomp"]);
}
con.Close();
return _items;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Dispose();
con.Close();
}
}
我认为这不是问题,请参见MSDN sample()。无论如何,我尝试了一次,并进行了更正,但应用程序仍不时在同一位置冻结。@rfc1484,我没有提出asnwer,而是要求您简化代码以更好地理解和简化。我更改了它,但问题仍然存在。@rfc1484,我建议目前使用实体框架,我无法测试您的应用程序,但可能是reader。Close()在这里是错误的,但请参阅中的示例实体框架用法,为了避免这种情况,您的问题是使用EF的简单linq。这是在后台线程上运行的吗?它是windows CE应用程序。应用程序从一个具有不同选项的菜单开始,此代码来自其中一个选项。当在菜单中选择一个选项时,将出现一个表示该选项的新表单,并且该菜单表单将保留。
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
...
}
listBox1.DataSource = _items;
public List<string> getItems(string codigodestino, string pendiente)
{
List<string> _items = new List<string>();
SqlCeConnection con = new SqlCeConnection(Globals.conString);
string Qyery = "SELECT codbultocomp FROM envios WHERE codigodestino='" + codigodestino + "' AND estado='" + pendiente +"'";
try
{
con.Open();
SqlCeCommand cmd = new SqlCeCommand(Qyery, con);
cmd.CommandType = CommandType.Text;
SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
_items.Add((string)reader["codbultocomp"]);
}
con.Close();
return _items;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Dispose();
con.Close();
}
}
listBox1.DataSource = getItems(codigoDestino, "pendiente");