2016-04-06 44 views
0

我在將存儲過程加載到DataGridView時遇到問題。我搜索了一個答案,但是我的代碼看起來與我找到的每個答案都相似。該存儲過程在我添加的另一個DataGridView中運行,我將它作爲一個固定的數據源包含在其中。我是C#的新手。任何人都可以看到我要去哪裏嗎?從存儲過程中加載DataGridView

private void Form1_Load(object sender, EventArgs e) 
    { 
     DataTable dt = new DataTable(); 
     SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True"); 
     myConn.Open(); 
     SqlCommand myCmd = new SqlCommand("spCustomers", myConn); 
     myCmd.CommandType = CommandType.StoredProcedure; 
     SqlDataAdapter da = new SqlDataAdapter(myCmd); 
     da.Fill(dt); 
     dataGridView1.DataSource = da; 

    } 
+0

什麼是this.iTManagementSystemDataSet?它似乎沒有在Form's Load事件中初始化。 – ManoDestra

+0

對不起,這是從我的代碼中刪除,我編輯了我的帖子。 – CodeRanger

回答

2

您無法綁定到SqlDataAdapter。您需要綁定到DataTable。

 DataTable dt = new DataTable(); 
     SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True"); 
     myConn.Open(); 
     SqlCommand myCmd = new SqlCommand("spCustomers", myConn); 
     myCmd.CommandType = CommandType.StoredProcedure; 
     SqlDataAdapter da = new SqlDataAdapter(myCmd); 
     da.Fill(dt); 
     dataGridView1.DataSource = dt; 
     dataGridView1.DataBind(); 

對於背景下,SqlDataAdapter的

表示一組數據命令和被 用於填充DataSet和更新SQL Server數據庫的數據庫連接。這個類 不能被繼承。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx

+1

完美謝謝:)我沒有添加行dataGridView1.DataBind();因爲我認爲這只是Web表單需要的。 – CodeRanger

+0

太好了。我不確定它是一個Windows或Web應用程序。 –

0

私人的BindingSource bindingSource1 =新的BindingSource();

DataTable dt = new DataTable(); SqlConnection myConn = new SqlConnection(「Data Source = SERVER-SQL1; Initial Catalog = OPSystem; Integrated Security = True」);

myConn.Open(); 
    SqlCommand myCmd = new SqlCommand("spCustomers", myConn); 
    myCmd.CommandType = CommandType.StoredProcedure; 
    SqlDataAdapter da = new SqlDataAdapter(myCmd); 
    da.Fill(dt); 

bindingSource1.DataSource = dt; dataGridView1.DataSource = bindingSource1;

試試BindingSource