2009-08-13 11 views
0

ドロップダウンリストコントロールを設定しようとしています。 「入力」はDBです。テーブルは '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

1行で複数の列があり、各列がドロップダウンリストに入力される場合はどうなりますか?私の質問はここにあります:http://stackoverflow.com/questions/30310610/how-to-split-sql-query-result-to-populate-a-dropdownlist – SearchForKnowledge

0

は、私はあなたがしばらくやってみたいと思います(reader.read())

はその後、その後データセットまたはリストのようなものを移入し、データセットまたはリストにリストデータソースドロップダウンを設定します。

0

テーブル名が "ApplicationName"の場合... SQL文がSELECT * FROM ApplicationNameであるべきではありませんか?あなたの読者に結果があるかどうかを調べようとしましたか?

0

あなたのDropDownListコントロールの定義でDataTextFieldとDataValueFieldを使用してデータベースクエリで選択した列に一致する場合は、あなただけ行う必要がある必要があります。

DropDownList1.DataSource = theReader; 
DropDownList1.DataBind() 

あるいは

DropDownList1.DataSource = theCommand.ExecuteReader(); 
関連する問題