I've made the following code to fill a list with data from a database.
public List<Transactie> FillTransacties()
{
try
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT transactieID, opdrachtID, medewerkerID, soort, datum, bedrag FROM Financien", connection);
SqlDataReader transactieinformatie = cmd.ExecuteReader();
List<Transactie> transacties = new List<Transactie>();
while (transactieinformatie.Read())
{
string transactieID = transactieinformatie["transactieID"].ToString();
string opdrachtID = transactieinformatie["opdrachtID"].ToString();
string medewerkerID = transactieinformatie["medewerkerID"].ToString();
string soort = transactieinformatie["soort"].ToString();
string datum = transactieinformatie["datum"].ToString();
string bedrag = transactieinformatie["bedrag"].ToString();
Transactie transactie = new Transactie(transactieID, opdrachtID, medewerkerID, soort, datum, bedrag);
transacties.Add(transactie);
connection.Close();
return transacties;
}
}
catch (InvalidCastException ICE)
{
MessageBox.Show("De data in de database is incorrect", ICE.Message);
return new List<Transactie>();
}
catch (Exception e)
{
MessageBox.Show("Er is een onbekende error opgetreden.", e.Message);
return new List<Transactie>();
}
}
Now I know what the problem is, I return values withing the while loop. The problem is though, when I try to 'Return transacties;' outside of the while loop, the List only fills with 1 value.
My question is then, how do I solve this error in such way that the database will fill with every row in the database?
You should rewrite your code with using
statements. These will automatically clean up the datareader, command, and connection once your code completes:
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT transactieID, opdrachtID, medewerkerID, soort, datum, bedrag FROM Financien", connection))
using (SqlDataReader transactieinformatie = cmd.ExecuteReader())
{
List<Transactie> transacties = new List<Transactie>();
while (transactieinformatie.Read())
{
string transactieID = transactieinformatie["transactieID"].ToString();
string opdrachtID = transactieinformatie["opdrachtID"].ToString();
string medewerkerID = transactieinformatie["medewerkerID"].ToString();
string soort = transactieinformatie["soort"].ToString();
string datum = transactieinformatie["datum"].ToString();
string bedrag = transactieinformatie["bedrag"].ToString();
Transactie transactie = new Transactie(transactieID, opdrachtID, medewerkerID, soort, datum, bedrag);
transacties.Add(transactie);
}
return transacties;
}
}
I've therefore removed the connection close from the loop (so you can continue reading more information), and now return the list outside the loop.