[英]C#: How to fill a ListView with data taken from PostgreSQL table?
我在这里需要C#的帮助...我正在尝试学习如何将表格与从PostgreSQL数据库获取的数据一起使用。 这就是为什么我的目标是从表中获取一些数据并将其插入到ListView中。 我的问题是:一旦启动包含ListView的Form,我就会得到一个异常,恰好是System.InvalidOperationException. The connection is not Open
System.InvalidOperationException. The connection is not Open
。 我不知道为什么,
这里有一些代码:
private void FormLoad(object sender, EventArgs e) {
list.View = View.Details;
list.GridLines = true;
list.FullRowSelect = true;
string connection = "Server=localhost;User Id=artemius;Password=prophet;" +
"Database=Exams;";
lista.Columns.Add("Course", 100);
lista.Columns.Add("CFU", 70);
lista.Columns.Add("Difficulty", 70);
ListViewItem item;
NpgsqlConnection conn;
try {
conn = new NpgsqlConnection(connection);
conn.Open(); //Isn't it opened here?
string sql = "select coursename, cfu, difficulty from courses where passed = false;";
string[] courses= new string[3];
NpgsqlCommand command = new NpgsqlCommand(sql);
/*--On Row Below I get System.InvalidOperationException--*/
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read()) {
courses[0] = dr[0].ToString();
courses[1] = dr[1].ToString();
courses[2] = dr[2].ToString();
item = new ListViewItem(corso);
lista.Items.Add(item);
}
conn.Close();
}
catch(NpgsqlException ecc) {
Console.WriteLine(ecc.BaseMessage);
}
}
你们有解决问题的想法吗? 谢谢
您尚未关联connection
和command
更换
NpgsqlCommand command = new NpgsqlCommand(sql);
通过
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.