c# - 数据绑定(bind)问题 asp.net 下拉列表

标签 c# asp.net data-binding

我试图绑定(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/

相关文章:

c# - ASP.Net 本地化(卫星程序集与带有自定义 ResourceProvider 的数据库)

c# - 如果 XAML 中的字符串太长,则自动在标签中下一行

c# - WPF 绑定(bind) : How to bind a name from a list of filepaths to text of TextBlock in ListBox?

c# - C# 闭包对内存有什么影响?

c# - 读写装箱双值线程安全且无锁?

c# - 如何在后面的aspx代码中访问用户控件控件

c# - 从客户端检测到具有潜在危险的 Request.QueryString 值

javascript - 如何轻松确定 $scope.$watch 中添加/删除的内容?

c# - 如何显示带有内容的星号矩形?

c# - 从 Web API url 中删除 "api"前缀