Search code examples
c#sql-serversqlconnectionexecutereader

Fill datagridview with SQL Server table data


I'm trying to fill a datagridview with SQL Server table data and I get an error:

ExecuteReader: Connection property has not been initialized.

How do I fix this ?

private void BlackListLoad()
{
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand();
        BindingSource bs = new BindingSource();

        var table = dt;
        var connection =
            @"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

        using (var con = new SqlConnection { ConnectionString = connection })
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            try
            {
                cmd.CommandText = @"SELECT * FROM [dbo].[Blacklist1]";
                table.Load(cmd.ExecuteReader());

                bs.DataSource = table;
                ListGrid.ReadOnly = true;
                ListGrid.DataSource = bs;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message + " sql query error.");
            }
        }
}

Solution

  • You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:

    cmd.Connection = con; just before you execute the reader.

    Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

    It also looks like you're not opening your connection, which can be fixed with:

    con.Open();

    With a new connection object, you do not need to check whether it's open, because it won't be.