Question

I'm using C# 2010 Express and Sql Compact. I have a table named as "Records" and column named as "Names" I want to list that names in a listbox.

I wrote that code but last line is thorws "ExecuteReader: Connection property has not been initialized." exception.

  SqlCeConnection Baglan = new SqlCeConnection("Data Source=|DataDirectory|CeoDatabase.sdf;Password=CeoDB;Persist Security Info=True");

        Baglan.Open();

    SqlCeCommand BarlariAl = new SqlCeCommand("SELECT Names FROM Barlar");

    SqlCeDataReader BarlariOku = BarlariAl.ExecuteReader();
Was it helpful?

Solution

As to what to write next, assuming there's a list box named listbox (bold assumption given your variable names), you'd write:

while(BarlariOku.Read())
    listbox.Items.Add(BarlariOku["Names"]);

As an aside, you're not disposing your objects properly. It should look like this:

using(var conn = new SqlCeConnection("Data Source=|DataDirectory|CeoDatabase.sdf;Password=CeoDB;Persist Security Info=True"))
{
    conn.Open();

    var comm = new SqlCeCommand("SELECT Names FROM Barlar", conn);
    SqlCeDataReader reader = comm.ExecuteReader();

    while(reader.Read())
        listbox.Items.Add(reader["Names"]);
}

OTHER TIPS

You're not associating the connection with the command. Try the code below.

SqlCeCommand BarlariAl = new SqlCeCommand("SELECT Names FROM Barlar", Baglan);

For listing the columns, try this code borrowed from MSDN (with closing braces added).

string query = "SELECT [Order ID], [Customer] FROM Orders";
SqlCeConnection conn = new SqlCeConnection(connString);
SqlCeCommand cmd = new SqlCeCommand(query, conn);

conn.Open();
SqlCeDataReader rdr = cmd.ExecuteReader();

try
{
    // Iterate through the results
    //
    while (rdr.Read())
    {
        int val1 = rdr.GetInt32(0);
        string val2 = rdr.GetString(1);
    }
}
finally
{
    // Always call Close when done reading
    //
    rdr.Close();

    // Always call Close when done reading
    //
    conn.Close();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top