如何根据下拉列表进行datalist更改?

时间:2017-07-21 03:34:13

标签: c# asp.net database visual-studio webforms

我正在尝试创建一个食物网页,我使用datalist来显示我的数据库中的食物,我将有一个关于烹饪类型的下​​拉列表,例如中文,西文,马来文,印度文。我如何编码我的datalist,以便当用户从下拉列表中选择Malay时,datalist将显示来自数据库的所有Malay食物,当用户选择中文时,datalist将更改并显示来自数据库的所有中国食物。

1 个答案:

答案 0 :(得分:0)

我在我的代码中使用了硬编码数据。您可以替换您的数据库表列表值进入PageLoad中的foodlist(WebForm.aspx.cs)

这是我的WebForm1.aspx Html代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication8.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="All">All</asp:ListItem>
        <asp:ListItem Value="Chinese">Chinese</asp:ListItem>
        <asp:ListItem Value="western">western</asp:ListItem>
        <asp:ListItem Value="Malay">Malay</asp:ListItem>
        <asp:ListItem Value="Indian">Indian</asp:ListItem>



    </asp:DropDownList>
    </div>

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>

    </form>
</body>
</html>

我的模特

public class food
    {
        public int foodId { get; set; }

        public string foodName { get; set; }

        public string foodtypes { get; set; }
    }

WebForm.aspx.cs文件

namespace WebApplication8
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        List<food> foodlist = new List<food>();
        protected void Page_Load(object sender, EventArgs e)
        {
            food fod = new food();
            fod.foodId = 1;
            fod.foodName = "testA";
            fod.foodtypes = "Chinese";

            foodlist.Add(fod);

            food fod1 = new food();
            fod1.foodId = 2;
            fod1.foodName = "testb";
            fod1.foodtypes = "Chinese";
            foodlist.Add(fod1);

            food fod3 = new food();
            fod3.foodId = 3;
            fod3.foodName = "testc";
            fod3.foodtypes = "Malay";
            foodlist.Add(fod3);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedDropdownlist = DropDownList1.Text;

            GridView1.DataSource = foodlist.Where(x => x.foodtypes == selectedDropdownlist).ToList();

            GridView1.DataBind();
        }
    }
}

我的用户界面 enter image description here