繁体   English   中英

无法将 C# 列表绑定到 ASP.net 中的 DropDownList

[英]Trouble binding C# list to DropDownList in ASP.net

过去一个小时左右,我一直在用头撞墙,因为在这个看似直截了当的过程中,我无法弄清楚自己做错了什么。

这是 ASPX 页面的样子:

<%@ Page Title="Teams" Language="C#" AutoEventWireup="true" CodeBehind="TeamEntry.aspx.cs" Inherits="Team.Model" Runat="server" Debug="true"%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <asp:DropDownList
            runat="server" 
            ID="DDL_Teams" 
            Width="183px">
        </asp:DropDownList>
        <input id="Text1" type="text" /><input id="Submit1" type="submit" value="submit" />
    </form>
</body>
</html>

这是背后的代码:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using Team;

namespace Team
{
    public partial class TeamEntry : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                using (var DDL_Teams = new DropDownList())
                {
                    DDL_Teams.DataSource = TeamsList;
                    DDL_Teams.DataBind();
                }
            }
        }

        List<string> TeamsList = new List<string>()
        {
            "Alpha", "Bravo", "Charlie", "Delta"
        };
    }
}

...但是当我尝试运行该页面时,我看到的只是一个空的下拉列表

我尝试了其他 StackOverflow 问题中提到的其他几种方法,这些问题与数据绑定到下拉列表(例如, 本页上列出的那些)有关,但无济于事。 任何帮助将非常感激。

您每次都根据此代码创建一个新的下拉列表

using (var DDL_Teams = new DropDownList())

这就是没有发生绑定的原因。

但需要使用 HTML 中创建的下拉列表 ID。 请在 TeamEntry.aspx.cs 中使用此代码

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DDL_Teams.DataSource = TeamsList;
                DDL_Teams.DataBind();

            }


        }
        List<string> TeamsList = new List<string>()
        {
            "Alpha", "Bravo", "Charlie", "Delta"
        };

删除服务器端代码上的下拉列表:

if (!IsPostBack) 
        {
            //using (var DDL_Teams = new DropDownList()) - Comment this line
            {
                DDL_Teams.DataSource = TeamsList;
                DDL_Teams.DataBind();
            }
        }

您的 web 表格上已经有DDL_Teams 尝试清理您的解决方案并重建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM