Display DropDownList in aspx-page
I created dropdownlist in C# code. How to display this ddlist in aspx page? My code:
<%
DropDownList list;
for (int i = 0; i < 10; i++)
开发者_Go百科 {
list = new DropDownList();
list.ID = i + "_ID";
%>
<!-- how to display drop down list here??? -->
<%
}
%>
Here is what I have in aspx code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DenemeWebForm1.aspx.cs" Inherits="DenemeWebApplication.DenemeWebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Panel ID="PanelAmk" runat="server">
<table>
<tr>
<td>
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
This code creates a web page with a panel named PanelAmk
, and nothing more.
Here is what I have in aspx.cs code(C# code) which basically adds a DropDownList
to the page created above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DenemeWebApplication
{
public partial class DenemeWebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList dropdownlistAmk = new DropDownList();//creates a new dropdownlist
dropdownlistAmk.Items.Add("amk");//adds an item to dropdownlistAmk created above
PanelAmk.Controls.Add(dropdownlistAmk);//and adds dropwdownlistAmk to PanelAmk
}
}
}
What you are missing is adding the DropDownList
to the control with ...Controls.Add(...)
Since you've created the control in code, The control doesn't yet exist on the page. You need to add it somewhere on the page. For example, you can decoratively create a asp:Panel with an ID of "myPanel" and then add ddlist through code as follows:
myPanel.Controls.Add(ddlist);
For a full description of this process, take a look at the following MSDN article: How to: Add Controls to an ASP.NET Web Page Programmatically
精彩评论