2017-12-14 14 views
0

SQL ServerテーブルのデータをDataGridViewのと、私はエラーを取得しますか?塗りつぶし、私はSQL ServerテーブルのデータとのDataGridViewを埋めるためにしようとしている

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

あなたは接続を開く必要があります: 'con.Open();'。そして、反対に、あなたはそれを閉じようとしています。 –

答えて

2

SqlCommandに接続していません。あなたがこれを行う必要があると述べているので。これを解決するには、リーダーを実行する直前に

cmd.Connection = con;を実行します。

詳細については、こちらをお読み

:新しい接続オブジェクトで

con.Open();

、あなたは:あなたがして固定することができ、あなたの接続を開いていないようですが、また見えhttps://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

開いていないかどうかを確認する必要はありません。

+0

返信いただきありがとうございました。私は文が乱れている場合もありました:) – Luka

+0

あなたの問題は今修正されましたか? – Jaxi

+0

はい問題は解決されています。誰かがそれを見つけたら、私はコードを修正して更新しました。 – Luka

0

この方法で試してください。

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"; 
     } 
    } 
} 
関連する問題