2

我的数据库中有 4 个对象,例如 zen、maruthi 和 scorpio ..将值绑定到下拉列表后,我只能看到 scorpio 重复 3 次..

而不是把它当作

zen
maruthi
scorpio 

..我得到天蝎座

scorpio 
scorpio..

代码

List<Cab> CabTypeList = new List<Cab>();
using (DataTable table = SqlDBConnector.ExecuteSelectCommand("GetCabType", CommandType.StoredProcedure))
{
    //check if any record exist or not
    if (table.Rows.Count > 0)
    {
        //Lets go ahead and create the list of cab

        foreach (DataRow row in table.Rows)
        {
            cab.CabType =  row["CabType"].ToString();
            cab.CabId = Convert.ToInt32(row["Cab_Id"]);
            CabTypeList.Add(cab);
        }
    }
}

ASPX 页面

if (!IsPostBack)
{
    CabDbAccess cabdbaccess = new CabDbAccess();
    DropDownList1.DataSource = cabdbaccess.GetCabType();
    DropDownList1.DataTextField = "CabType"; // the items to be displayed in the list items
    DropDownList1.DataValueField = "CabId"; // the id of the items displayed
    DropDownList1.DataBind();
}
4

2 回答 2

2

cab来自哪里?确保在foreach循环中添加新项目。

public List<Cab> GetCabType()
{  
   List<Cab> CabTypeList = new List<Cab>();
   // to do : get your data in the data table. 
   foreach (DataRow row in table.Rows)
   {
     var cab= new Cab();
     cab.CabType =  row["CabType"].ToString();
     cab.CabId = Convert.ToInt32(row["Cab_Id"]);
     CabTypeList.Add(cab);
   }
   return CabTypeList;
}
于 2012-11-05T05:01:51.020 回答
0

不管cab是什么,你都加了三遍。您最终在列表中有三个项目都是相同的对象。您可能想 Cab cab = new Cab();在循环顶部添加类似的内容。然后,您将每次添加一个不同的。

于 2012-11-05T05:04:40.793 回答