2013-07-10 45 views
0

我想填充窗體上的組合框。我有存儲過程來獲取我的ComboBoxes的數據。我的代碼如下。問題是我的組合框沒有被填充。當我遍歷代碼時,它會到達「reader = sc.ExecuteReader();」並且不會執行Pop_ComboBox()中的任何後續行。存儲過程返回「ID」和「Description」(僅)。我究竟做錯了什麼?未從存儲過程填充組合框

private void frmInput_Load(object sender, EventArgs e) 
    { 
     //Connect to the db 
     this.sqlConn = new SqlConnection("Server=\"our_server";Database=\"Astra\";Trusted_Connection=yes;"); 

     //Populate the Equipment Type Listbox 
     Pop_ComboBox("exec uspASTRA_GetEquipTypeList;", cboEquipType); 


    } 

    private void Pop_ComboBox(string sQuery, ComboBox NameOfcbo) 
    { 
     SqlCommand sc = new SqlCommand(sQuery, this.sqlConn); 
     SqlDataReader reader; 

     reader = sc.ExecuteReader(); 
     DataTable dt = new DataTable(); 

     dt.Columns.Add("ID", typeof(int)); 
     dt.Columns.Add("Description", typeof(string)); 
     dt.Load(reader); 

     NameOfcbo.ValueMember = "ID"; 
     NameOfcbo.DisplayMember = "Description"; 
     NameOfcbo.DataSource = dt; 

    } 
+0

您可能會在調用ExecuteReader時發生異常。在Visual Studio中,進入'Debug-> Exceptions',檢查一切並再次調試。或者將調用放入try-catch塊並查看異常。 –

+0

你還沒有打開你的連接...... !! this.sqlConn.Open(); –

+0

@Azhar - 感謝您的支持!並感謝達里奧的建議。我現在看到我的SqlConn工作不正常。 – johncroc

回答

0

,所以我想這個總結成一個令人信服的答案我自己的問題。但是,我需要把它應該歸功於哪裏,因爲如果不是來自其他人的偉大想法,我不能回答。

首先,我需要一個圍繞我的代碼的Try-Catch塊。如果我有這樣的話,我會得到我沒有很好連接到數據庫的信息。謝謝Dario-Ramos!

其次,我需要一個很好的連接字符串,並顯式連接到數據庫。明顯。謝謝你,阿茲哈羅拉薩尼!

最後,Eslam賈邁勒的建議,我需要設置的命令類型爲「存儲過程」,並執行如下:

sc.CommandType = CommandType.StoredProcedure; 
SqlDataReader dr = sc.ExecuteReader(); 

謝謝大家的建議。我學到了一些有價值的課程,並且我的組合框被填充!

1

使用SqlDataAdapter並填充您的數據表。 e.g:

http://www.dotnetperls.com/sqldataadapter

然後結合你的組合框與數據表的數據源。

+0

我很好奇:爲什麼DataAdapter比只讀數據集的DataReader更好?或者你是否在提出建議,因爲我正嘗試使用它,因此無法使用數據讀取器? – johncroc

+0

現在我有了一個很好的連接到數據庫,我原來的代碼(使用SqlDataReader)完美的作品。 – johncroc

0

精確設置命令類型爲StoredProcedure

sc.CommandType = CommandType.StoredProcedure; 

和不使用exec只使用StoredProc名