2014-12-03 71 views
0

您好,我想讓DropDownList與SqlDataReader一起工作,但是它沒有填充DropDownlist。 TextBox.Text閱讀器正在工作。DropDownList不與SqlDataReader一起工作

這裏是我使用的代碼:

using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString)) 
    { 
     SqlCommand command = 
     new SqlCommand("SELECT * FROM [datarep].[dbo].[OrderHeader] WHERE [OrderNumber] = '"+OrderNumber+"'", con); 
     con.Open(); 

     SqlDataReader read = command.ExecuteReader(); 

     while (read.Read()) 
     { 
      TextBox2.Text = (read["CreatedDate"].ToString()); 
      TextBox3.Text = (read["CreatedBy"].ToString()); 
      CompanyStored = (read["CustomerID"].ToString()); 
      TextBox7.Text = (read["Store_Number"].ToString()); 

      DropDownList1.DataTextField = (read["Year"].ToString()); 
      DropDownList1.DataBind(); 



     } 
     read.Close(); 
    } 
+0

有多少物品被添加到'DropDownList ..?還要將你的'DropDownList1.DataBind();'移出While循環,並查找如何將'DataSource賦值給DropdownList' – MethodMan 2014-12-03 21:07:02

+0

只添加1個項目@DJKRAZE – 2014-12-03 21:07:40

+0

好,如果碰巧有更多我仍然會移動它也看看這[MDSN綁定數據DropDownList](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist%28v=vs.110%29.aspx) – MethodMan 2014-12-03 21:08:54

回答

0

SqlDataReader的逐行讀取數據線。如果你想使用DataReader你必須每次迭代新列表項添加到您的DDL

試試這樣說:

while (read.Read()) 
{ 
    /*code omitted*/ 
    var item = new ListItem(); 
    item.Text = read["Year"].ToString(); 
    item.Value = read["Year"].ToString(); 
    DropDownList1.Items.Add(item); 
} 

進一步閱讀和替代方案:

+0

我得到這個錯誤DataBinding:'System.Data.Common.DataRecordInternal'不包含名稱爲'2013'的屬性@Serv – 2014-12-03 21:09:39

+0

在哪一行你會得到這個錯誤? – Marco 2014-12-03 21:13:21

+0

DropDownList1.DataBind(); – 2014-12-03 21:13:57

1

假設您的下拉列表已經填充了年份列表,您需要設置它的值而不是設置它的DataTextField - 該屬性用於定義文本的數據源的列或屬性名稱,而不是設置選定的值本身。

DropDownList1.SelectedValue = read["Year"].ToString(); 

如果你沒有下拉人口甚至還沒有,那麼你必須填充它提前,使用數據源,這也許是多年的列表。例如,假設你想2000年至2050年之間的所有日子裏,這樣的事情可能做的伎倆:

var dataSource = Enumerable.Range(2000, 51) 
    .Select(x => new { TheYear = x }) 
    .ToArray(); 

DropDownList1.DataSource = dataSource; 
DropDownList1.DataValueField = "TheYear"; 
DropDownList1.DataTextField = "TheYear"; 
DropDownList1.DataBind(); 

注意,DataTextField和DataValue字段表示數據源對象的屬性。

對於像數字一樣簡單的事情,您也可以一次填充下拉列表,而不是使用數據源 - 最後的結果是相同的。