2009-08-13 68 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();