2009-08-13 65 views
0

我試圖填充下拉列表控件。 '輸入'是數據庫。表是'ApplicationName',它有一個賦值給它的隨機值。SQL值不填充ASP DropDownList控件

出於某種原因,當我單擊「測試提交」按鈕時,控件中沒有任何內容出現(DropDownList1)。

protected void TestSubmit_ServerClick(object sender, EventArgs e) 
{ 
    // Initialize the database connector. 
    SqlConnection connectSQL = new SqlConnection(); 

    // Send the connection string. 
    connectSQL.ConnectionString = @"Data Source = localhost\SQLEXPRESS;" + 
     "Initial Catalog = Inputs; Integrated Security = SSPI"; 

    try 
    { 
     // Setup our command. 
     SqlCommand theCommand = new SqlCommand("SELECT * FROM Inputs", connectSQL); 

     // Write the stored value in the text boxes. 
     connectSQL.Open(); 

     SqlDataReader theReader; 

     theReader = theCommand.ExecuteReader(); 
     theReader.Read(); 

     DropDownList1.Items.Add(theReader["ApplicationName"].ToString()); 

     theReader.Close(); 
     connectSQL.Close(); 
    } 
    catch (Exception ee) 
    { 
     MessageBox("Oopsie: " + ee); 
}  

回答

4

您是否考慮過使用SqlDataSource?這對於你維護和防範缺陷的代碼將少得多。

 <asp:DropDownList id="DropDownList1" 
      runat="server" 
      DataTextField="ApplicationName" 
      DataValueField="ApplicationName" 
      DataSourceID="AppDataSource"> 
     </asp:DropDownList> 

    <asp:SqlDataSource 
      id="AppDataSource" 
      runat="server" 
      DataSourceMode="DataReader" 
      ConnectionString="<%$ ConnectionStrings:MyNorthwind%>" 
      SelectCommand="SELECT ApplicationName FROM Inputs"> 
    </asp:SqlDataSource> 
+0

如果我有一行但多列,並且每列將填充下拉列表,該怎麼辦?我的問題在這裏:http://stackoverflow.com/questions/30310610/how-to-split-sql-query-result-to-populate-a-dropdownlist – SearchForKnowledge 2015-05-18 18:43:56

0

我想你想要做的一段時間(reader.read())

然後填充像一個數據集或列表,然後設置下拉列表中的數據源的數據集或列表。

0

如果你的表名是「ApplicationName」......你的SQL語句不應該是SELECT * FROM ApplicationName?您是否試圖查看您的讀者是否有任何結果?

0

如果匹配與DataTextField和DataValueField在定義你的DropDownList數據庫查詢選擇的列,你應該只需要做:

DropDownList1.DataSource = theReader; 
DropDownList1.DataBind() 

甚至

DropDownList1.DataSource = theCommand.ExecuteReader();