数据库中的下拉列表

时间:2016-10-13 16:34:14

标签: c# asp.net database visual-studio drop-down-menu

I cant see the dropdown list I created (click this link for image)

以下是我在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],开胃菜,甜点,饮料)

----我想看看&#34;开胃菜,甜点,饮料&#34;在下拉列表中,来自数据库,在我的网页

1 个答案:

答案 0 :(得分:1)

您需要将查询更改为:

        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();