从对象列表填充下拉列表
在尝试构建一个 3 层架构的 c# asp.net 应用程序时,我开始构建一个数据库类,用于连接到数据库,另一个类是 City,它为数据库中的每一列都有一个方法。表城市和 Cities 类,其中我有 GetCities 方法,该方法创建 City 对象列表,然后使用 DataSource 向导将控件设置为使用 GetCities() 中的数据。 我得到的只是下拉列表中的空白。知道为什么吗?
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;
}
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否设置了 DataTextField、DataValueField 属性并调用 DataBind?
此时,我会尝试尽可能简单地让这个概念发挥作用,然后开始添加一些内容,直到找到问题为止。从一个全新的页面开始,添加一个 DropDownList 但不要触摸数据源或更改任何属性,直接进入代码隐藏并将其添加到 Page_Load 中:
它有效吗?对我来说确实如此。然后尝试更改 DataValueField、DataTextField 和 DataSource 以使用您的客户列表。现在坏了吗?然后您就知道问题出在客户列表的某个地方,而不是您绑定数据的方式。
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:
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.
您是否在要填充的对象上调用了 DataBind() 方法?
Have you called DataBind() method on the object you want to be populated ?
问题出在 City 类中,经过仔细检查,我意识到构造函数分配的参数不正确。现在已经开始工作了。谢谢!
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!