2014-04-24 28 views
0

我正在使用以下代碼填充我的DropDownList;DropDownList填寫失敗; DataValueField始終爲最低值

while (myDataReader.Read()) 
       { 

        DropDownList1.Items.Add(myDataReader[0].ToString()); 
        DropDownList1.DataValueField = myDataReader[1].ToString(); 
        DropDownList1.DataTextField = myDataReader[0].ToString(); 

       } 

但不管是什麼在DropDownList1選擇時,DataValue總是從while循環讀取的最後一個DataValue。

我在做什麼錯?

回答

0

而不是使用myDataReader的,我綁定的下拉列表的數據源

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString); 

SqlCommand cmd = new SqlCommand("Select * from students", con); 

SqlDataAdapter da = new SqlDataAdapter(cmd); 

DataSet ds = new DataSet(); 
da.Fill(ds); 

DropDownList1.DataTextField = ds.Tables[0].Columns["FullName"].ToString(); 
DropDownList1.DataValueField = ds.Tables[0].Columns["id"].ToString(); 

DropDownList1.DataSource = ds.Tables[0]; 
DropDownList1.DataBind(); 
-1

所以它看起來像你想使用數據庫列名稱作爲數據值字段。但是你實際上提供了列值而不是列名作爲數據值字段。您的代碼應該是這樣的:

DropDownList1.DataValueField = "ValueColumn"; //name of the value column, such as 'id' from the database 
DropDownList1.DataTextField = "NameColumn"; //name of the descriptive column, such as 'name' 
while (myDataReader.Read()) 
{ 
    //also, we removed the 'ToString' because we want to provide the datarow object, not the converted string value 
    DropDownList1.Items.Add(myDataReader[0]); 
} 
+0

在具有DropDownList1.Items.Add線路(myDataReader [0]);我得到一個「不能從'對象'轉換爲'字符串' – CryptoJones

+0

對不起,我的錯誤。你應該使用.Add(myDataReader [0] .ToString(),myDataReader [1] .ToString());或類似的東西。看到 http://forums.asp.net/t/1287909.aspx?How+to+add+items+in+Drop+Down+List+ – Richthofen

+0

如果我嘗試將它分配給一個局部變量,它只是返回「ValueColumn 「(文字字符串) – CryptoJones