rfc1484
rfc1484

Reputation: 9837

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

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?

Upvotes: 3

Views: 2140

Answers (3)

CrazyMPh
CrazyMPh

Reputation: 580

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");

Upvotes: 1

Saeed Amiri
Saeed Amiri

Reputation: 22555

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;

Upvotes: 1

Zenwalker
Zenwalker

Reputation: 1919

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.

Upvotes: 0

Related Questions