我正在使用C#2010 Express和Sql Compact。我有一个名为“Records”的表和名为“Names”的列我想在列表框中列出这些名称。
我编写了该代码,但最后一行是thorws“ExecuteReader:Connection属性尚未初始化。”异常。
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();
答案 0 :(得分:2)
至于接下来要写什么,假设有一个名为listbox
的列表框(给出变量名称的粗体假设),你会写:
while(BarlariOku.Read())
listbox.Items.Add(BarlariOku["Names"]);
顺便说一句,你没有妥善处理你的物品。它应该是这样的:
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"]);
}
答案 1 :(得分:0)
您没有将连接与命令相关联。请尝试下面的代码。
SqlCeCommand BarlariAl = new SqlCeCommand("SELECT Names FROM Barlar", Baglan);
要列出列,请尝试从MSDN借用的代码(添加结束括号)。
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();
}