Looks like you didn't initialize your SqlCommand.Connection
property. Without this, your program can't know to execute your SqlCommand
using which SqlConnection
. Just add;
cmd.Connection = cn;
cn.Open();
...
Or you can pass your SqlConnection
to your SqlCommand
constructor as a second parameter (which I always prefer) like;
SqlCommand cmd = new SqlCommand("select * from Szelvenyek", cn);
Also use using
statement to dispose your SqlConnection
, SqlCommand
and SqlDataReader
like;
using(SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Iskola\C#\lotto_kerekeshunor\lotto_kerekeshunor\Database1.mdf;Integrated Security=True;User Instance=True"))
using(SqlCommand cmd = new SqlCommand("select * from Szelvenyek", cn))
{
cn.Open();
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
{
///
}
}
}