locked
How to select distinct value in dropdownlist? RRS feed

  • Question

  • User-1647172364 posted

    Hlo 

    Currently i want to select distinct from my database and display into my dropdownlist, but my code doesn't work well.

    Here Is my Code

     public void Filldropdownlist()
            {
                using (SchoolEntities2 ctx = new SchoolEntities2())
     
     
                    dd3.DataSource = (from SchoolEntities2 in ctx.packages select SchoolEntities2).Distinct().ToList();
                   dd3.DataBind();
            }
    Monday, June 15, 2020 8:33 AM

All replies

  • Monday, June 15, 2020 8:01 PM
  • User1686398519 posted

    Hi,  sanam13

    • Since the code you gave is incomplete, the problem cannot be determined. Can you give your front-end code and the structure of the table? You can debug your code to see if data is returned. Can you give your error message?
    • In addition, you can refer to this link.

     Best Regards,

    YihuiSun

    Tuesday, June 16, 2020 6:17 AM
  • User-1647172364 posted
    Aspx
    
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Model.aspx.cs" Inherits="WebApplication14.Model" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content3" ContentPlaceHolderID="body" runat="server">
    
        
                   <div style="margin-top:30px; margin-left:20px">
            
                     
                       <h1><strong style="color:black">Entity Fm 6.0</strong></h1>    
                       <hr />
               
        <table>
                       
                
         <tr>
                        <td><span style="color:black">Package Name</span><br />
                        <asp:TextBox ID ="tb_name"  runat="server" Width="200px"   /><br />
            
          
                        </td>
    
                       <td><span style="margin-left:25px; color:black">Reward<br /></span>
                        <span style="margin-left:25px">
                            <asp:DropDownList ID="dd3" runat="server" Width="200px" DataTextField="reward">
                            
    
                                                       </asp:DropDownList></span> <br />
           
                       </td>
                         
                        <td><span style=" margin-left:25px; color:black">Remarks</><br /></span>
                        <span style="margin-left:25px"><asp:TextBox ID="tb_remarks" runat="server" Width="410px" /></span> <br />
          
                        </td>
                      
             </tr>
    
                              
         <tr>   
             <td>     
            <br /> <asp:Button ID="BT_submit" runat="server"  Text="Submit" style="border-radius:5px" Height="35px" Width="80px"   OnClick="BT_submit_Click" BackColor="#3366CC" BorderColor="#3366CC" ForeColor="White"  />
           
         </td>
             <td>
               <br /><asp:Button ID="BT_update" runat="server"   Text="Update" style="border-radius:5px; margin-left:1.5em" Height="35px" Width="80px"   OnClick="BT_update_Click" BackColor="#3366CC" BorderColor="#3366CC" ForeColor="White" />
          <asp:Label ID="id" runat="server"></asp:Label>
             </td>
                  <td><br /><asp:Button ID="BT_delete" runat="server" Text="Delete" style=  " margin-left:1.6em;    border-radius:5px" Height="35px" Width="80px"  OnClick="BT_delete_Click" BackColor="#3366CC" BorderColor="#3366CC"  ForeColor="White" /> </td>
           
    
             </tr>
    
    
    
        </table></div>
    
        <div style="margin-top:30px; margin-left:20px">
            
             <asp:gridview runat="server" ID="Gv8" AutoGenerateColumns="False" BackColor="#3366CC" GridLines="Both"  
                 BorderColor="#3366CC"  OnRowCancelingEdit="Gv8_RowCancelingEdit"  OnRowDataBound="Gv8_RowDataBound" OnRowEditing="Gv8_RowEditing"
     OnRowDeleting="Gv8_RowDeleting" OnRowUpdating="Gv8_RowUpdating"   BorderStyle="None" BorderWidth="1px" CellPadding="3" Width="80%" DataKeyNames="tbl_id">
         
            <Columns>
             <%--               <asp:BoundField DataField="package_name" HeaderText="Package Name" /> 
                              <asp:BoundField DataField="reward" HeaderText="Reward" /> 
                              <asp:BoundField DataField="remarks" HeaderText="Remarks" /> --%>
                <asp:TemplateField HeaderText="Package Name" >
                                     <ItemTemplate>
                                         <%# Eval("package_name") %>
    
                                     </ItemTemplate>
                                     <EditItemTemplate>
                                         <asp:TextBox ID="TB_pack" runat="server" Text='<%# Eval("package_name") %>'  />
    
                                     </EditItemTemplate>
    
                                 </asp:TemplateField>
                                
             
              <asp:TemplateField HeaderText="Reward">
                                    
                                    <ItemTemplate>
    
                             <%# Eval("reward") %>
    
                                      </ItemTemplate>
                       
                                    <EditItemTemplate>
                                          <asp:textbox ID="TB_rewar" runat="server" Text='<%# Eval("reward") %>'  >
    
                                          </asp:textbox>
                                     
                                                                  
                                   
                                    </EditItemTemplate>
    
    
                                </asp:TemplateField>
             
             
             
             
             
             <asp:TemplateField HeaderText="Remarks" >
                                     <ItemTemplate>
                                         <%# Eval("reward") %>
    
                                     </ItemTemplate>
                                     <EditItemTemplate>
                                         <asp:TextBox ID="TB_remark" runat="server" Text='<%# Eval("remarks") %>'  />
    
                                     </EditItemTemplate>
    
                                 </asp:TemplateField>
                             
            <%-- <asp:TemplateField>
                <ItemTemplate>
                     <asp:LinkButton runat="server" ID="link" Text="Edit" OnClick="link_Click"></asp:LinkButton>
                 </ItemTemplate>
                 
             </asp:TemplateField>--%>
                          <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
         
                             </Columns>
                 <FooterStyle BackColor="#3366CC" ForeColor="#3366CC" />
                 <HeaderStyle BackColor="#3366CC" Font-Bold="True" ForeColor="Window" />
                 <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                 <RowStyle BackColor="White" ForeColor="#003399" />
                 <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                 <SortedAscendingCellStyle BackColor="#EDF6F6" />
                 <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
                 <SortedDescendingCellStyle BackColor="#D6DFDF" />
                 <SortedDescendingHeaderStyle BackColor="#002876" />
             </asp:gridview>
               
                    
                                 
               
    
    
    
        </div>
    
    </asp:Content>
    
    C#
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    
    namespace WebApplication14
    {
    
        public partial class Model : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    Fillgridview();
                    Filldropdownlist();
                }
            }
    
            public void Fillgridview()
            {
                using (SchoolEntities2 ctx = new SchoolEntities2())
    
    
                    Gv8.DataSource = (from SchoolEntities2 in ctx.packages select SchoolEntities2).ToList();
                    Gv8.DataBind();
            }
            public void Filldropdownlist()
            {
                using (SchoolEntities2 ctx = new SchoolEntities2())
    
    
                    dd3.DataSource = (from SchoolEntities2 in ctx.packages select SchoolEntities2).Distinct().ToList();
                   dd3.DataBind();
            }
            
            protected void BT_submit_Click(object sender, EventArgs e)
            {
                //model.package_name = tb_name.Text.Trim();
                //model.reward = tb_reward.Text.Trim();
                //model.remarks = tb_remarks.Text.Trim();
    
                int status = 0;
                using (SchoolEntities2 ctx = new SchoolEntities2())
                {
                    ctx.packages.Add(new package()
                    {
    
                        package_name = tb_name.Text,
                        reward = dd3.SelectedValue.ToString(),
                        remarks = tb_remarks.Text,
                        by_whom = Session["username"].ToString(),
                        date_time = System.DateTime.Now.ToLocalTime()
    
                    }) ;
    
                    
                    status = ctx.SaveChanges();
                    Fillgridview();
                    Filldropdownlist();
    }
            }
    
            protected void BT_update_Click(object sender, EventArgs e)
            {
               
                int status = 0;
                
                using (SchoolEntities2 ctx = new SchoolEntities2())
                {
    
                    
    
                    {
    
                        var on = ctx.packages.Where(a => a.tbl_id == 1).FirstOrDefault();
    
                        on.package_name = tb_name.Text;
                        on.reward = dd3.SelectedValue.ToString();
                        on.remarks = tb_remarks.Text;
                        on.by_whom = Session["username"].ToString();
                        on.date_time = System.DateTime.Now.ToLocalTime();
    
                    }
    
    
                    status = ctx.SaveChanges();
                    Fillgridview();
                }
    
            }
    
            protected void BT_delete_Click(object sender, EventArgs e)
            {
                int status = 0;
                using (SchoolEntities2 ctx = new SchoolEntities2())
                {
                    ctx.packages.Remove(new package()
                    {
    
                        //package_name = tb_name.Text,
                        //reward = tb_reward.Text,
                        //remarks = tb_remarks.Text,
                        //by_whom = Session["username"].ToString(),
                        //date_time = System.DateTime.Now.ToLocalTime()
    
                    });
    
    
                    status = ctx.SaveChanges();
                    Fillgridview();
                }
            }
    
           
    
            protected void Gv8_RowEditing(object sender, GridViewEditEventArgs e)
            {
                Gv8.EditIndex = e.NewEditIndex;
                Fillgridview();
            }
    
            protected void Gv8_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridViewRow row = Gv8.Rows[e.RowIndex];
                decimal Tbl_id = Convert.ToDecimal(Gv8.DataKeys[e.RowIndex].Values[0]);
    
    
                string packag = (row.FindControl("TB_pack") as TextBox).Text;
                string reward = (row.FindControl("TB_rewar") as TextBox).Text;
                string remarks = (row.FindControl("TB_remark") as TextBox).Text;
    
                using (SchoolEntities2 ctx = new SchoolEntities2())
                {
                    var package = (from c in ctx.packages
                                   where c.tbl_id == Tbl_id
                                   select c).FirstOrDefault();
    
                    package.package_name = packag;
                    package.reward = reward;
                    package.remarks = remarks;
    
    
                    ctx.SaveChanges();
    
                }
                Gv8.EditIndex = -1;
                Fillgridview();
            }
            protected void Gv8_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                decimal Tbl_id = Convert.ToDecimal(Gv8.DataKeys[e.RowIndex].Values[0]);
                using (SchoolEntities2 ctx = new SchoolEntities2())
                {
                    var package = (from c in ctx.packages
                                   where c.tbl_id == Tbl_id
                                   select c).FirstOrDefault();
                    ctx.Entry(package).State = System.Data.Entity.EntityState.Deleted;
                    ctx.SaveChanges();
    
                }
                Gv8.EditIndex = -1;
                Fillgridview();
            }
    
                   
    
            protected void Gv8_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                Gv8.EditIndex = -1;
                Fillgridview();
            }
            protected void Gv8_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != Gv8.EditIndex)
                {
                    //(e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
                }
            }
    
            //    protected void link_Click(object sender, EventArgs e)
            //    {
    
            //    }
    
        }
    }
    

    Tuesday, June 16, 2020 7:22 AM
  • User1686398519 posted

    Hi sanam13,

    You can use "DistinctBy" to fulfill your needs.

            public void Filldropdownlist()
            {
                using (SchoolEntities2 ctx = new SchoolEntities2())
                dd3.DataSource = (from SchoolEntities2 in ctx.packages select SchoolEntities2).ToList().DistinctBy(p=>p.reward);
                dd3.DataBind();
            }

    Here is the result.

     

    Best Regards,

    YihuiSun

    Wednesday, June 17, 2020 10:50 AM
  • User-1647172364 posted

    Hlo Sir

    I have applied ur given code but again the error is occuring.

    getting error on distinct by

    Gv8.DataSource = (from SchoolEntities2 in ctx.packages select SchoolEntities2).ToList().DistinctBy(p=>p.package_name);

     

    "List<package>' does not contain a definition for 'DistinctBy' and no accessible extension method 'DistinctBy' accepting a first argument of type 'List<package>' could be found (are you missing a using directive or an assembly reference?) WebApplication14 F:\Asp Projects\WebApplication14\WebApplication14\Model1.aspx.cs 27 Active"

    Monday, June 22, 2020 6:08 AM
  • User1686398519 posted

    Hi sanam13,

    You can check if you reference "using Microsoft.Ajax.Utilities;".

    Best Regards,

    YihuiSun

    Tuesday, July 7, 2020 9:12 AM
  • User-943250815 posted

    Did try solution in article I alredy post?
    LINQ: Distinct() does not work as expected
    http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

    Tuesday, July 7, 2020 1:52 PM