下拉列表值重复

时间:2012-11-05 04:55:27

标签: c# asp.net data-binding

我的数据库中有4个对象,例如zen,maruthi和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();
}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

无论cab是什么,您都要添加三次。您最终在列表中有三个项目都是同一个对象。您可能希望在循环顶部添加Cab cab = new Cab();之类的内容。然后你每次都会添加一个不同的。

相关问题