Luka
Luka

Reputation: 25

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.");
            }
        }
}

Upvotes: 1

Views: 6119

Answers (2)

ASH
ASH

Reputation: 20352

Try it this way.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
            string sql = "SELECT * FROM Authors";
            SqlConnection connection = new SqlConnection(connectionString);
            SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            connection.Open();
            dataadapter.Fill(ds, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "Authors_table";
        }
    }
}

Upvotes: 1

Sasha
Sasha

Reputation: 1724

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.

Upvotes: 2

Related Questions