开发者

How to use a list of strings as listbox's datasource

开发者 https://www.devze.com 2023-03-28 15:15 出处:网络
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>();

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 show开发者_开发百科s 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?


Call it after your using, all IDisposable objects will be disposed after using.

...
List<string> _items = new List<string>(); 
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
     ...
} 

listBox1.DataSource = _items;


Why don't you try something like this:

For a clear code create a method like:

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();
    }
}

and then just use:

listBox1.DataSource = getItems(codigoDestino, "pendiente");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消