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、あなたはそれを3回追加しています。最終的に、すべて同じオブジェクトである3つのアイテムがリストに含まれることになります。Cab cab = new Cab();おそらく、ループの先頭に次のようなものを追加する必要 があります。次に、毎回個別に追加します。

于 2012-11-05T05:04:40.793 に答える