[英]databinding issue asp.net dropdown list
我试图绑定我的下拉列表,我认为是因为前端的ASP代码未绑定
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();
不应该在这里,只需将其删除即可。 您已经初始化了下拉菜单。
第二个问题-如果您希望某些默认项出现在列表中,则应在数据绑定之后插入它:
populattePage();
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
ListItem具有属性“文本”和“值”。 因此,当您创建一个时,只能将这些属性用于下拉列表的文本/值字段。 你需要改变
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Text"
DataValueField="Value" AutoPostBack="True" >
</asp:DropDownList>
一种获取您的位置的简单方法是
List<ListItem> locations = (from a in dc.Locations
select new ListItem()
{
Text = a.Name,
Value = a.Name
}).ToList();
然后将其添加到您的列表。
因此,问题在于您要绑定的数据源主要是字符串。 设置DataValueField和DataTextField属性时,它将调用反射器并要求将其绑定到对象以为其提供属性。 由于我假设查询中的a.Name是字符串,因此它将没有“ Name”或“ Id”属性。 一个简单的解决方案是创建一个ID和Name属性。
这可能有助于说明我要说的话。 (如果您打算使用C#,也请用驼峰式表示您的函数名称,这有助于我们维护程序员:))
public static void GetLocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
var locations = (
from a
in dc.Locations
select new { Name = a.Name, Id = a.Id }).ToList(); // this can be Id = a.Name or whatever too
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.