Reputation: 513
i have 4 objects in my database eg zen ,maruthi and scorpio ..after binding the values to dropdown list i can only see scorpio repeated 3 times ..
instead of getting it as
zen
maruthi
scorpio
..i get scorpio
scorpio
scorpio..
Code
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 page
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();
}
Upvotes: 2
Views: 1041
Reputation: 4641
Whatever cab
is, you're adding it three times. You end up having three items in your list that are all the same object. You probably want to add something like Cab cab = new Cab();
at the top of the loop. Then you'll add a distinct one each time.
Upvotes: 0
Reputation: 218762
Where is cab
coming from ? Make sure you are adding a new item in the foreach
loop.
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;
}
Upvotes: 2