我试图绑定(bind)我的下拉列表,我认为是因为我在前端的 asp 代码没有以某种方式绑定(bind)
aspx
<asp:Label ID="Label2" runat="server" />
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Name"
DataValueField="Name" AutoPostBack="True" >
</asp:DropDownList>
C#代码
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label0.Text = "Specialities";
Label1.Text = "Category";
Label2.Text = "Locations";
ddSpec.Items.Insert(0, new ListItem("Select a spec", "0"));
ddCategory.Items.Insert(0, new ListItem("Select a Category", "0"));
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
populattePage();
}
}
public void populattePage()
{
getlocation();
// getCategory()
}
public static void getlocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
List<string> locations = (
from a
in dc.Locations
select a.Name).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
我现在有错误“”“”DataBinding:“System.String”不包含名称为“Name”的属性。“”““页面加载”“”类中的代码将项目添加到下拉菜单但是当我调用获取位置类时出现此错误,请提前帮助感谢
最佳答案
这里有两个问题。首先 - 如果您要使用 Location 对象的 2 个属性,您应该使用该对象作为数据源。没有必要为此提取单独的字符串列表:
ddLocation.DataSource = dc.Locations.ToList();
这将解决您的异常。还有这一行:
DropDownList ddLocation = new DropDownList();
不应该在这里,去掉就行了。您已经初始化了下拉菜单。
第二个问题 - 如果您希望某些默认项出现在列表中,您应该将其插入数据绑定(bind)之后:
populattePage();
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
关于c# - 数据绑定(bind)问题 asp.net 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22100200/