【问题标题】:Trouble binding C# list to DropDownList in ASP.net无法将 C# 列表绑定到 ASP.net 中的 DropDownList
【发布时间】:2020-08-14 09:38:07
【问题描述】:

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

这是 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"
        };
    }
}

...但是当我尝试运行该页面时,我看到的只是an empty dropdown list

我尝试了其他 StackOverflow 问题中提到的与数据绑定到下拉列表相关的其他几种方法(例如,this page 中列出的方法),但均无济于事。任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

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

    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"
            };
    

    【讨论】:

    • 感谢您的回复!但是,当我尝试在没有 using (var DDL_Teams = new DropDownList()) 的情况下执行此操作时,它会引发错误,提示“当前上下文中不存在 DDL_Teams”。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 2011-04-16
      • 2010-11-18
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多