开发者

populate dropdown list from a list of objects

开发者 https://www.devze.com 2023-01-31 16:35 出处:网络
In an attempt of building a 3-tier architecture c# asp.net application, I\'ve started building a class that is database which is used for the connecting to the database开发者_高级运维, another class t

In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database开发者_高级运维, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities(). All I get is blanks in the dropdown list. Any idea why?

        public List<City> GetCities()
    {
        List<City> cities = new List<City>();
        Database db = new Database();
        SqlConnection conn = db.GetConnection();
        String sql = "SELECT * FROM CITIES";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
            cities.Add(c);
        }

        db.CloseConnection();
        return cities;
    }

thanks


Did you set the DataTextField, DataValueField properties, and call DataBind?


At this point I would try to get the concept working as simply as possible, and then start adding things back in until you locate the problem. Start with a brand new page, add a DropDownList but don't touch the data source or change any properties, go directly into the codebehind and add this in Page_Load:

DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = new[] {
    new { ID = 1, Name = "Alice" },
    new { ID = 2, Name = "Mike" },
    new { ID = 3, Name = "John" }
};
DropDownList1.DataBind();

Does it work? It does for me. Then try to change DataValueField, DataTextField, and DataSource to work with your customer list. Is it broken now? Then you know the problem is in the customer list somewhere, not with the way you're binding the data.


Have you called DataBind() method on the object you want to be populated ?


The issue resided in the City class which after a close inspection I've realised that the constructor was assigning the parameter received incorrectly. It's now working. Thanks!

public class City
{
    int id;
    string name;

    public City(int id, string name)
    {
        this.id = id;
        this.name = name;

    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public String Name
    {
        get { return name; }
        set { name = value; }
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消