在ASP.net中将C#列表绑定到DropDownList时出现问题



在过去的一个小时左右,我一直在用头撞墙,因为我不知道在这个看似直截了当的过程中我做错了什么。

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

删除服务器端的Dropdownlist代码:

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

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

最新更新