简体   繁体   中英

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:

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:

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

CategoryTypes(Category [PK], Appetizers, Desserts, Beverages)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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