使用SQL Server表数据填充datagridview

时间:2017-12-14 14:01:26

标签: c# sql-server sqlconnection executereader

我正在尝试使用SQL Server表数据填充datagridview,但是出现错误:

  

ExecuteReader:尚未初始化Connection属性。

我该如何解决这个问题?

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

2 个答案:

答案 0 :(得分:2)

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

cmd.Connection = con;就在您执行阅读器之前。

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

看起来您还没有打开连接,可以通过以下方式修复:

con.Open();

使用新的连接对象,您无需检查它是否已打开,因为它不会。

答案 1 :(得分:1)

以这种方式试试。

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