简体   繁体   English

C#/ ASP.NET以编程方式生成带有选项的select元素

[英]C#/ASP.NET programmatically generated a select element with options

I would like to generate a select box with options using C#/ASP.NET. 我想使用C#/ ASP.NET生成一个带有选项的选择框。

How would I go about doing this? 我将如何去做呢? I can do it in PHP or Python, however in C# I figure I have to use a .cs file? 我可以用PHP或Python做到这一点,但是在C#中我认为我必须使用.cs文件?

Are there any controls I need to put on the main ASPX page? 我需要在ASPX主页上放置任何控件吗?

I want to pull a list of names and ids from a MySQL database, insert the name as the option to be selected, and the id as the value, and have that all show up on the page. 我想从MySQL数据库中提取名称和ID的列表,将名称作为要选择的选项插入,将ID作为值插入,并在页面上全部显示。

I'm not sure how C# interacts between .aspx and .aspx.cs in this scenario. 在这种情况下,我不确定C#如何在.aspx和.aspx.cs之间进行交互。

Basically you would have a Dropdownlist control bound to a Datasource control in your .aspx page. 基本上,您将在.aspx页中将Dropdownlist控件绑定到Datasource控件。 The Datasource control will use a connection string you have defined in your web.config file to connect to your mysql database. Datasource控件将使用您在web.config文件中定义的连接字符串连接到mysql数据库。

The .aspx.cs contains the code for when you postback to the server after, for example, selecting a name in your Dropdownlist . .aspx.cs包含用于例如在Dropdownlist选择一个名称后回发到服务器的代码。 If you are using Visual Studio, most of it can be done through the UI. 如果您使用的是Visual Studio,则大多数操作都可以通过UI完成。

using System.Web.UI.WebControls;
...
DropDownList ddl = new DropDownList();
ddl.DataSource = [your data source];
ddl.Databind();
ddl.DataTextField = [field to show]
ddl.DataValueField = [value]

Page.Controls.Add(ddl);

You'll find examples here: 您可以在此处找到示例:

DataBinding DropDownList in C#/ASP.NET C#/ ASP.NET中的DataBinding DropDownList

http://www.codeproject.com/Tips/303564/Binding-DropDownList-Using-List-Collection-Enum-an http://www.codeproject.com/Tips/303564/Binding-DropDownList-Using-List-Collection-Enum-an

And the basics: 和基础:

http://asp.net-tutorials.com/basics/code-behind/#.UH7-zsWlXO4 http://asp.net-tutorials.com/basics/code-behind/#.UH7-zsWlXO4

And a quick example: 一个简单的例子:

The aspx file: aspx文件:

<body>
<form id="form1" runat="server">
<div>
    <asp:DropDownList ID="myDDL" runat="server" DataTextField="MyTextField" DataValueField="MyValueField" />
</div>
</form>

The code behind file: 文件后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    myDDL.DataSource = myDataTable;
    myDDL.DataBind();
  }
}

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

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