Reputation: 354
I need some help with C# here...
I'm trying to learn how to use Forms with Data taken from a PostgreSQL database.
That's why my aim is to take some data from a table and insert this data into a 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
.
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
Upvotes: 0
Views: 391
Reputation: 17846
You haven't associated the connection
and the command
Replace
NpgsqlCommand command = new NpgsqlCommand(sql);
by
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
Upvotes: 1