[英]C#: How to fill a ListView with data taken from PostgreSQL table?
I need some help with C# here... I'm trying to learn how to use Forms with Data taken from a PostgreSQL database. 我在这里需要C#的帮助...我正在尝试学习如何将表格与从PostgreSQL数据库获取的数据一起使用。 That's why my aim is to take some data from a table and insert this data into a ListView. 这就是为什么我的目标是从表中获取一些数据并将其插入到ListView中。 My problem is: as soon I start the Form containing the ListView I get an exception, precisely System.InvalidOperationException. The connection is not Open
我的问题是:一旦启动包含ListView的Form,我就会得到一个异常,恰好是System.InvalidOperationException. The connection is not Open
System.InvalidOperationException. The connection is not Open
. System.InvalidOperationException. The connection is not Open
。 I have no idea why, 我不知道为什么,
Here some code: 这里有一些代码:
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);
}
}
Do you guys have any idea how to solve the issue? 你们有解决问题的想法吗? Thank you 谢谢
You haven't associated the connection
and the command
您尚未关联connection
和command
Replace 更换
NpgsqlCommand command = new NpgsqlCommand(sql);
by 通过
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.