简体   繁体   English

数据库中的下拉列表

[英]Dropdown list from database

I cant see the dropdown list I created (click this link for image) 我看不到我创建的下拉列表(单击此链接获得图像)

Here is my code in add.aspx.cs: 这是我在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();
    }
}

In database I created 2 tables: 在数据库中,我创建了2个表:

Categories(CatID [PK], Category[FK]) 类别(CatID [PK],类别[FK])

CategoryTypes(Category [PK], Appetizers, Desserts, Beverages) CategoryTypes(类别[PK],开胃菜,甜品,饮料)

---- I want to see the "Appetizers, Desserts, Beverages" in the dropdown list which is from database, in my webpage ----我想在我的网页的数据库下拉列表中看到“开胃菜,甜点,饮料”

You need to change the query to: 您需要将查询更改为:

        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.

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