2013-11-01 195 views
0

即時通訊試圖填補下拉列表,這讓我只有一個值。我怎樣才能把從數據庫中給出的所有值?填充下拉列表

var con = new SqlConnection("server=(local);Initial Catalog=Test;Integrated Security=True"); 

try 
{ 
    con.Open(); 
    SqlCommand command = new SqlCommand("GetDates", con); 
    command.CommandType = CommandType.StoredProcedure; 

    command.Parameters.Add(new SqlParameter("@Dates", SqlDbType.DateTime, 50, ParameterDirection.Output, false, 0, 50, "Dates", DataRowVersion.Default, null)); 
    command.Parameters.Add(new SqlParameter("@Hours", SqlDbType.NChar, 10, ParameterDirection.Output, false, 0, 50, "Hours", DataRowVersion.Default, null)); 
    command.UpdatedRowSource = UpdateRowSource.OutputParameters; 
    command.ExecuteNonQuery(); 
    DateTime Dates = (DateTime)command.Parameters["@Dates"].Value; 
    string Hours = (string)command.Parameters["@Hours"].Value; 


    day.Items.Add(Hours); 



} 
catch (Exception ex) 
{ 
    con.Close(); 
} 

這是SP

ALTER PROCEDURE GetDates (@Dates datetime OUTPUT, @Hours NCHAR(10) OUTPUT) 
AS 
    SELECT @Dates = Dates, @Hours = Hours from test..Dates where taken = 0 
GO 
+0

爲什麼ExecuteNonQuery?使用ExecuteReader或任何其他方式獲取結果集,然後使用LINQ將其放入DDL。 – LINQ2Vodka

回答

0

你可以改變GetDates存儲過程返回Dates, Hours像下面

ALTER PROCEDURE GetDates() 

    AS 
     SELECT Dates, Hours from test..Dates where taken = 0 
    GO 

然後

con.Open(); 
SqlCommand command = new SqlCommand("GetDates", con); 
command.CommandType = CommandType.StoredProcedure; 
DataTable dt = new DataTable(); 
dt.Load(command.ExecuteReader()); 
day.DataSource = dt; 
day.DataTextField = "Hours"; 
day.DataValueField = "Dates"; 
day.DataBind(); 
+0

我編輯並把我使用的SP與2個輸出值。當我做你的解決方案,它不填充德dropdownlist,任何想法? – JpCrow

+0

@ user2631328無需輸出值,使用select語句 – Damith

+0

這項工作完美,它填補所有的下拉列表,THX Damith。 – JpCrow

0
 DataSet DropDownListValues = urclassname.GetDates(); 

     DataRow dr; 

     DropDownList1.Items.Clear(); 

     DropDownList1.Items.Add(""); 

     if (DropDownListValues.Tables[0].Rows.Count > 0) 
     { 
      int k = 0; 

      while (k < DropDownListValues.Tables[0].Rows.Count) 
      { 
       dr = DropDownListValues.Tables[0].Rows[k]; 

       string Hours = dr["Hours"].ToString().Trim(); 

       string Dates = dr["Dates"].ToString().Trim(); 

       DropDownList1.Items.Add(new ListItem(Hours , Dates)); 

       k++; 
      } 
     }