使用 SQL 服务器 table 数据填充 datagridview

Fill datagridview with SQL Server table data

我正在尝试用 SQL 服务器 table 数据填充数据网格视图,但出现错误:

ExecuteReader: Connection property has not been initialized.

我该如何解决这个问题?

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

您还没有为您的 SqlCommand 提供连接!正如它所说,你需要这样做。您可以通过以下方式解决此问题:

cmd.Connection = con; 就在您执行 reader.

之前

阅读此处了解更多信息:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

您似乎还没有打开连接,这可以通过以下方式解决:

con.Open();

对于新的连接对象,您不需要检查它是否打开,因为它不会。

这样试试。

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