[英]Dropdown list from database
這是我在add.aspx.cs中的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//ADO.NET
using System.Data;
using System.Data.SqlClient;
using System.IO;
public partial class Admin_Users_Add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(kmb.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategoryTypes();
}
}
/// <summary>
/// Allows the user to display list of user types
/// from the table Types to the dropdownlist control
/// </summary>
void GetCategoryTypes()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Category FROM Categories";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "Category";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();
}
}
在數據庫中,我創建了2個表:
類別(CatID [PK],類別[FK])
CategoryTypes(類別[PK],開胃菜,甜品,飲料)
----我想在我的網頁的數據庫下拉列表中看到“開胃菜,甜點,飲料”
您需要將查詢更改為:
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Appetizers +', '+ Desserts +', '+ Beverages as CatDescription FROM Categories Inner Join CategoryTypes ON Categories.Category = CategoryTypes.Category";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "CatDescription";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.