[英]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.