How to bind LINQ data to dropdownlist

Ranjeet_8
Posted by Ranjeet_8 under LINQ category on | Points: 40 | Views : 8602
Add this code on .ASPX page

<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

Write this code on .Aspx.CS page

using System.Collections.Generic;
public class ClsEmployees
{
public string EmpID { get; set; }
public string Name { get; set; }
public Int32 Salary { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ClsEmployees> objEmployee = new List<ClsEmployees>
{
new ClsEmployees { EmpID = "1001" ,Name ="IBM", Salary =11000 },
new ClsEmployees { EmpID = "1002" ,Name ="HCL", Salary =11000 },
new ClsEmployees { EmpID = "1003" ,Name ="TCS", Salary =11000 },
new ClsEmployees { EmpID = "1004" ,Name ="WIPRO", Salary =31000 },
new ClsEmployees { EmpID = "1005" ,Name ="SATHYAM", Salary =42000 },
new ClsEmployees { EmpID = "1006" ,Name ="BUTTERFLY", Salary =50000 },
new ClsEmployees { EmpID = "1007" ,Name ="CON", Salary =11000 },
new ClsEmployees { EmpID = "1008" ,Name ="TVS", Salary =71000 },
new ClsEmployees { EmpID = "1008" ,Name ="TVS", Salary =71000 },
new ClsEmployees { EmpID = "1010" ,Name ="TATA", Salary =90000 },
new ClsEmployees { EmpID = "1009" ,Name ="GANTEC_COR", Salary =100000 },
new ClsEmployees { EmpID = "1009" ,Name ="GANTEC_COR", Salary =100000 },
};
// Linq Select Distinct query
var EmpList = (from emp in objEmployee select new { emp.EmpID, emp.Name }).Distinct();
DropDownList1.DataValueField = "EmpID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = EmpList;
DropDownList1.DataBind();
}
}

Comments or Responses

Login to post response