How can i show Data from a class into a gridview?
MY Class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class EmployeeDetails
{
private int employeeID;
public int EmployeeID
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
private string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
private string titleOfCourtesy;
public string TitleOfCourtesy
{
get
{
return titleOfCourtesy;
}
set
{
titleOfCourtesy = value;
}
}
public EmployeeDetails(int employeeID, string firstName, string lastName, string titleOfCourtesy)
{
EmployeeID = employeeID;
FirstName = firstName;
LastName = lastName;
TitleOfCourtesy = titleOfCourtesy;
}
}
I`ve done this:
protected void Page_Load(object sender, EventArgs e)
{
int id = 15;
string f_name = "asd";
string l_name = "asd";
string title = "asd";
EmployeeDetails emp = new EmployeeDetails(id,f_name,l_name,title);
emp.EmployeeID = id;
emp.FirstName = f_name;
emp.LastName = l_name;
emp.TitleOfCourtesy = title;
}
List<EmployeeDetails> lst = new List<EmployeeDetails>() ;
GridView1.DataSource = lst ;
GrdiView1.DataBind();
you may populate the list with your EmployeeDetails Objects
A GridView is generally used to display multiple objects/rows. To get it to display your class you need to make a collection containing your class, such as a List<EmployeeDetails>. Then bind that to your gridview.
You could use another control more suited to displaying a single object such as a DetailsView.
I assume you are looking for an answer to show multiple item instead of just 1.
C#
var myList = List<EmploymentDetails>();
foreach (var employee in SomeOtherDataSource)
{
EmployeeDetails emp = new EmployeeDetails{EmployeeID = id, FirstName = f_name, LastName = l_name, TitleOfCourtesy = title};
myList.Add(emp);
}
var EmployeeDS = from eds in myList select new { ID = EmployeeID, FName = FirstName, LName = LastName, Title = TitleofCourtest };
MyGridview.DataSource = EmployeeDS;
MyGridView.DataBind();
By doing this: var EmployeeDS = from eds in myList select new { ID = EmployeeID, FName = FirstName, LName = LastName, Title = TitleofCourtest }; it makes it possible to just use <%# Eval('ID/FName/LName/Title'%> in the GridView's boundfields instead of those long variable names you've made in your entity class.
Related
I have a form (Edit) with some textbox controls as private members with public properties that I want to access from another class (PatientService) and I can't figure out how to overcome the "textbox does not exist in the current context" errors for the 8 controls I am trying to access. Also, is passing these values through the constructor a good way of doing this? I cannot have any other part of my project aside from the PatientService class interacting with the database. Thanks and the textboxes in question are in bold.
public partial class Edit : XtraForm
{
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
public Edit(string PatientID, string FirstName, string LastName, string Address, string City, string State, string ZipCode, string Phone)
{
InitializeComponent();
patientID = txtPatientID.Text;
firstName = txtFirstName.Text;
lastName = txtLastName.Text;
address = txtAddress.Text;
city = txtCity.Text;
state = txtState.Text;
zipCode = txtZipCode.Text;
phone = txtPhone.Text;
}
public string PatientID
{
get { return patientID; }
set { patientID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string ZipCode
{
get { return txtZipCode.Text; }
set { txtZipCode.Text = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public void CreatePatient()
{
//SAConnection conn = new SAConnection("dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
//SACommand cmd = new SACommand("INSERT INTO patient(patient_id, first_name, last_name, address, city, state, zipcode, phone) VALUES(); ");
using (SAConnection conn = new SAConnection())
{
conn.ConnectionString = "dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;";
conn.Open();
using (SACommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"insert into patient(\n" +
" patient_id,\n" +
" first_name,\n" +
" last_name,\n" +
" address,\n" +
" city,\n" +
" state,\n" +
" zipcode,\n" +
" phone)\n" +
" values(\n" +
" #prm_patient_id,\n" +
" #prm_first_name,\n" +
" #prm_last_name,\n" +
" #prm_address,\n" +
" #prm_city,\n" +
" #prm_state,\n" +
" #prm_zipcode,\n" +
" #prm_phone)";
cmd.Parameters.Add("#prm_patient_id", SADbType.VarChar, 80).Value = **txtPatientID.Text**;
cmd.Parameters.Add("#prm_first_name", SADbType.VarChar, 80).Value = **txtFirstName.Text**;
cmd.Parameters.Add("#prm_last_name", SADbType.VarChar, 80).Value = **txtLastName.Text**;
cmd.Parameters.Add("#prm_address", SADbType.VarChar, 80).Value = **txtAddress.Text**;
cmd.Parameters.Add("#prm_city", SADbType.VarChar, 80).Value = **txtCity.Text**;
cmd.Parameters.Add("#prm_state", SADbType.VarChar, 80).Value = **txtState.Text**;
cmd.Parameters.Add("#prm_zipode", SADbType.VarChar, 80).Value = **txtZipCode.Text**;
cmd.Parameters.Add("#prm_phone", SADbType.VarChar, 80).Value = **txtPhone.Text**;
cmd.ExecuteNonQuery();
}
}
}
Ok, so I'm still a little confused. I made the Patient class and instantiated it in the Edit form just like this.
public Patient pat;
public Edit(Patient patient)
{
InitializeComponent();
pat = patient;
}
I'm trying to get it to when I click on an "OK" button, the textbox controls are inserted into the database via a CreatePatient method in the PatientService class.
Here is the method from the Edit Form that invokes the CreatePatient method in the PatientService class:
private void btnOK_Click(object sender, EventArgs e)
{
PatientService ps = new PatientService();
ps.CreatePatient();
}
My Patient class looks like:
public class Patient
{
List<Patient> patList = new List<Patient>();
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
private int classificationID;
protected object Dispose;
public Patient(string PatientID, string FirstName, string LastName, string Address, string City, string State, string ZipCode, string Phone, int ClassificationID)
{
this.patientID = PatientID;
this.firstName = FirstName;
this.lastName = LastName;
this.address = Address;
this.city = City;
this.state = State;
this.zipCode = ZipCode;
this.phone = Phone;
this.classificationID = ClassificationID;
}
public string PatientId
{
get { return patientID; }
set { patientID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string ZipCode
{
get { return zipCode; }
set { zipCode = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public int ClassificationID
{
get { return classificationID; }
set { classificationID = value; }
}
public Patient(string PatientID)
{
this.patientID = PatientID;
}
public Patient()
{
}
}
}
So considering I am no longer passing values through the Edit constructor like in the beginning, how would I make use of the Patient class to get the textbox values sent to the database?
You do not need to access your controls from other form, or class.
Since you have public properties, you can access to it from parent form:
Edit form = new Edit(patientId, ...);
//after using form
string patientId = form.PatientID;
Better option is wrap your fields into a single object, like entity
public class Patient
{
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
//put here your properties
}
Use it in your Edit form
public partial class Edit : XtraForm
{
public Patient Patient;
public Edit() //empty constructor if you want to pass data manually via property
{
InitializeComponent();
}
public Edit(Patient patient)
{
InitializeComponent();
Patient = patient;
}
//full code here
}
You can always keep actual data in Patient object using EditValueChanged event form your text boxes (As far as I know you are using DevExpress controls, like XtraForm). For example:
private void txtPatientID_EditValueChanged(object sender, EventArgs e)
{
Patient.patientId = txtPatientID.Text;
}
You need to pass your form class to PatientService
For example:
public class PatientService
{
//your code
public Edit EditForm{get;set;}
}
Now you can pass Edit to PatientService:
somewhere:
var svc = new PatientService();
svc.EditForm = existEditForm;
You can access tour edit form from patient service now. Something like this:
EditForm.PatientId = "0";
I want to update some information when a save button is clicked.
I got an error
On : command.Parameters.Add("#doctorID", SqlDbType.Int).Value =
resident.Doctor.DoctorID; Saying: Object reference not set to an
instance of an object.
Im guessing I need to create some kind of object?
Button code:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
Resident residentID;
txtAdditionalInformation.Text = hello.addtionalInformation;
txtForename.Text = hello.FirstName;
txtSurname.Text = hello.Surname;
txtTitle.Text = hello.Title;
ResidentData.Update(hello);
}
update code (ResidentData Class):
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}
*Residence Class:
{
public class Resident
{
private int residentID;
private string title;
private string firstName;
private string surname;
private string searchText;
private System.DateTime dateOfBirth;
private byte[] photo;
private Room room;
private Doctor doctor;
private string nhs;
private string residentBarcode;
private string allergies;
private string additionalInformation;
public Resident()
: base()
{
}
public Resident(int newResidentID, string newTitle, string newFirstName, string newSurname, string newSearchText, System.DateTime newDateOfBirth, byte[] newPhoto, Room newRoom, Doctor newDoctor, string newNhs, string newResidentBarcode, string newAllergies, string newAdditionalInformation)
: base()
{
residentID = newResidentID;
title = newTitle;
firstName = newFirstName;
surname = newSurname;
searchText = newSearchText;
dateOfBirth = newDateOfBirth;
photo = newPhoto;
room= newRoom;
doctor = newDoctor;
nhs = newNhs;
residentBarcode = newResidentBarcode;
allergies = newAllergies;
additionalInformation = newAdditionalInformation;
}
public int ResidentID
{
get { return residentID; }
set { residentID = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string SearchText
{
get { return searchText; }
set { searchText = value; }
}
public System.DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public byte[] Photo
{
get { return photo; }
set { photo = value; }
}
public Room Room
{
get { return room; }
set { room = value; }
}
public Doctor Doctor
{
get { return doctor; }
set { doctor = value; }
}
public string NHS
{
get { return nhs; }
set { nhs = value; }
}
public string ResidentBarcode
{
get { return residentBarcode; }
set { residentBarcode = value; }
}
public string Allergies
{
get { return allergies; }
set { allergies = value; }
}
public string addtionalInformation{
get { return additionalInformation; }
set { additionalInformation = value; }
}
}
}
Looking at the way you've created your Resident:
Resident hello = new Resident();
ucMedicationCheckIn.SaveCheckedInMedication();
ResidentData.Update(hello);
ucMedicationCheckIn.HideDetails();
you probably haven't assigned it a doctor which is why it fails on this line:
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
You need to initialize the Doctor type
Edit*
After seeing your Resident class I can see that you haven't initialized Room either.
You could provide a constructor to initialize these to default values:
public Resident()
{
this.Doctor = new Doctor();
this.Room = new Room();
//etc...
}
Though to do anything meaningful you will probably want to set these up with actual data before saving.
That is because your Doctor and Room are not initialized anyhere:
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
but that update will probably fail as there is no meaningful data in resident and rowsAffected will return 0 probably.
In my table, I have a field of firstname and lastname, now what I want is to set firstname and lastname as displaymember in a combobox, but I don't know how to do it.
Something like this
cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "lastname, first_name";
cmbEmployees.ValueMember = "id";
How can I achieve this? So that both lastname and firstname will be displayed in the combobox
This example will guide you how to do that without modifying your base class.
First, you can leave your DisplayMember with one property, let's say:
cmbEmployees.DisplayMember = "lastname";
Now, go to your form in a [Design] mode,
right click on the ComboBox -> Properties.
In the top of the Properties window, click on Events (lightning icon),
look for Format in the events list below (under Property Changed) and type there some event name, let's say: ComboBoxFormat , and press Enter. You will see this:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
}
And now write these following lines inside:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
// Assuming your class called Employee , and Firstname & Lastname are the fields
string lastname = ((Employee)e.ListItem).Firstname;
string firstname = ((Employee)e.ListItem).Lastname;
e.Value = lastname + " " + firstname;
}
That's it ;)
Let's say you had a class like this:
class Person
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string FullName
{
get
{
return LastName + ", " + FirstName;
}
}
public Person(string firstname, string lastname)
{
FirstName = firstname;
LastName = lastname;
}
}
If you don't have a FullName property, just create one in the format you wish to display the name. Then set the DisplayMember equal to FullName.
Your query should be like this in GetEmployees() function.
"SELECT id,(lastname + ' ' + first_name) AS NAME FROM TABLE"
cmbEmployees.DataSource = GetEmployees();
cmbEmployees.DisplayMember = "NAME";
cmbEmployees.ValueMember = "id";
in C# 6 create readonly property in your Employee class
public string FullName=>$"{lastname} {firstname}";
then
cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "FullName";
cmbEmployees.ValueMember = "id";
Try one of those approaches:
new Dictionary with concatenated fields as value - https://stackoverflow.com/a/1006588/1816426
calculated column - https://stackoverflow.com/a/1006546/1816426
CREATE VIEW [dbo].[get_view]
AS
SELECT CONCAT(sell_tb.Name,extra_tb.Name,purchase_tb.Name) AS Name FROM sell_tb FULL JOIN extra_tb ON extra_tb.E_ID = sell_tb.E_ID
FULL JOIN purchase_tb ON purchase_tb.S_ID = sell_tb.S_ID;
private void alldata1()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [get_view]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
conn.Close();
}
// Declare a class
private class ComboRec
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Department { get; set; }
}
// Fill the Combo Items
private void FillMyComboList()
{
EmployeesCombo.Items.Clear();
EmployeesCombo.ValueMember = "ID";
EmployeesCombo.DisplayMember = "FullName";
MySqlCommand cmd = new MySqlCommand("select id, firstname, lastname, department from employees order by lastname, firstname", MyConnection);
cmd.Transaction = myTransaction;
MySqlDataReader rdr = cmd.ExecuteReader();
ComboRec comborec;
while (rdr.Read())
{
comborec = new ComboRec();
comborec.ID = rdr["id"].ToString();
comborec.FirstName = rdr["firstname"].ToString();
comborec.LastName = rdr["lastname"].ToString();
comborec.FullName = rdr["lastname"].ToString() + ", " + rdr["firstname"].ToString();
comborec.Department = rdr["department"].ToString();
EmployeesCombo.Items.Add(comborec);
}
rdr.Close();
}
// Get the values from combo
string id = ((ComboRec)EmployeesCombo.SelectedItem).ID);
string firstname = ((ComboRec)EmployeesCombo.SelectedItem).FirstName);
string lastname = ((ComboRec)EmployeesCombo.SelectedItem).LastName);
string fullname = ((ComboRec)EmployeesCombo.SelectedItem).FullName);
string department = ((ComboRec)EmployeesCombo.SelectedItem).Department);
public void alldata1()
{
var Person= context.Person.Select(s => new {
display = s.surName+" "+s.name,
value = s.studentID
});
comboBoxStudentNom.DataSource = Person.ToList();
comboBoxStudentNom.ValueMember = "value";
comboBoxStudentNom.DisplayMember = "display";
}
My program has textboxes and a listView and info is typed into the textboxes and then displayed into the listview at the click of a button. the info is ID, first name, last name and yearly salary. The info is stored in array.
I want to find the person with the lowest salary. How do I go about doing this? (in C#)
this is my Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace Employee_Program
{
public partial class Form1 : Form
{
public Form1()
{
em = new ArrayList();
InitializeComponent();
}
public ArrayList em = new ArrayList();
private void show_employee()
{
listView1.Items.Clear();
foreach(Employee a in em)
{
int i = listView1.Items.Count;
listView1.Items.Add(a.EmployeeId.ToString());
listView1.Items[i].SubItems.Add(a.FirstName);
listView1.Items[i].SubItems.Add(a.LastName);
listView1.Items[i].SubItems.Add(a.YearSalary.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
Employee a = new Employee();
a.EmployeeId = float.Parse(employeeId.Text);
a.FirstName = firstName.Text;
a.LastName = lastName.Text;
a.YearSalary = float.Parse(yearSalary.Text);
em.Add(a);
show_employee();
}
private void button2_Click(object sender, EventArgs e)
{
// this is the button that will return the lowest salary value. Preferably in a
//message box? Any idea?
}
}}
this is my class, Employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Employee_Program
{
class Employee
{
protected float employeeId;
protected string firstName;
protected string lastName;
protected float yearSalary;
// first constructor
public Employee()
{
employeeId = 0;
firstName = "";
lastName = "";
yearSalary = 0;
}
// second constructor
public Employee(float EmployeeId, string FirstName,
string LastName, float YearSalary)
{
employeeId = EmployeeId;
firstName = FirstName;
lastName = LastName;
yearSalary = YearSalary;
}
public float EmployeeId
{
get
{
return employeeId;
}
set
{
employeeId = value;
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
public float YearSalary
{
get
{
return yearSalary;
}
set
{
yearSalary = value;
}
}
}
}
Note: Be sure to include:
using System.Linq;
You can use a LINQ expression such as:
Employee[] employees;
//Populate employees
var min = (from e in employees select e.YearSalary).Min();
MoreLINQ has a MinBy method. If you don't want to use MinBy, there are several ways to do it. I recommend this approach:
// Don't use an ArrayList, use a List<Employee>
Employee minEmp = employees.Aggregate(float.MinValue, (min, e) => (e.YearSalary < min.YearSalary) ? e : min);
If you need a list of all the employees with matching minimum salary, you could do something like this:
float min = employees.Min(e => e.YearSalary);
var minEmps = employees.Where(e => e.YearSalary == min);
Consider about refactoring your code.
you can use chain constructors to avoid initialization duplication
you can use auto-properties
its very strange that you use float as id. consider using something like int
usually camelCase used for parameters naming
consider using decimal type for salary
Your Employee class is much cleaner now:
public class Employee
{
public Employee()
: this(0, "", "", 0)
{
}
public Employee(int employeeId, string firstName,
string lastName, decimal yearSalary)
{
EmployeeId = employeeId;
FirstName = firstName;
LastName = lastName;
YearSalary = yearSalary;
}
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set;}
public decimal YearSalary { get; set; }
}
consider using NumericUpDown control for numeric values input
consider using descriptive names for controls
consider adding new employee to the end of listView, instead of reloading all employees
consider using generic list for employees collection
usually PascalCase used for methods naming
Here is Form1 code:
private List<Employee> employees = new List<Employee>();
private void ShowEmployee(Employee employee)
{
var item = employeeListView.Items.Add(employee.EmployeeId.ToString());
item.SubItems.Add(employee.FirstName);
item.SubItems.Add(employee.LastName);
item.SubItems.Add(employee.YearSalary.ToString());
}
private void AddEmployeeButton_Click(object sender, EventArgs e)
{
Employee employee = new Employee();
employee.EmployeeId = (int)idNumericUpDown.Value;
employee.FirstName = firstNameTextBox.Text;
employee.LastName = lastNameTextBox.Text;
employee.YearSalary = salaryNumericUpDown.Value;
employees.Add(employee);
ShowEmployee(employee);
}
private void LowestSalaryButton_Click(object sender, EventArgs e)
{
decimal minSalary = employees.Min(em => em.YearSalary);
MessageBox.Show(minSalary.ToString("C"), "Min salary");
}
Look into using a MinBy extension method. It's notably lacking in Linq. An implementation can be found here.
Then you'd simply:
Employee aCheapEmployee = employees.MinBy(e => e.Salary);
If you need to find all lowest paid employees:
var minSalary = employees.Min(e => e.Salary);
IEnumerable<Employee> slaveLabourers = employees.Where(e => e.Salary==minSalary);
I want to take a list of employees with 3 parts, employee id, last name and first name and add them to a drop down list showing last name, first name.
What I have so far is that I created a class for the employees:
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
and created a list to populate:
private List<Employee> employeeList = new List<Employee>();
this list is populated from a sql query and then sorted by last name.
foreach (DataRow row in ds.Tables["EMPLOYEE_TABLE"].Rows)
{
employeeList.Add(new Employee(int.Parse(row["EMP_ID"].ToString()),
row["LAST_NAME"].ToString(), row["FIRST_NAME"].ToString()));
}
employeeList.Sort(delegate(Employee E1, Employee E2) { return E1.lastName.CompareTo(E2.lastName); });
and everything up to that point worked exactly as I wanted it to but I cannot figure out how I populate a dropdownlist with the last name and first name values contained in the list.
code has been edited for readability
See code below:
DropDownList ddl = new DropDownList();
ddl.DataSource = employeeList;
ddl.DataTextField = "fullName";
ddl.DataValueField = "emp_Id";
I would also modify your class to include a full name field:
public class Employee
{
public int emp_Id { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
public string fullName
{
get
{
return String.Format("{0} {1}", this.firstName, this.LastName);
}
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
You could add an extra property to your class that will hold the 3 values, and use this as your DataTextField when binding the DropDownList:
Class Code
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string Text
{
get { return this.ToString(); }
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
public override string ToString()
{
return lastName + " " + firstName + " " + emp_Id;
}
}
HTML:
List<Employee> employees = new List<Employee>();
ddl.DataSource = employees;
ddl.DataValueField = "emp_Id";
ddl.DataTextField = "Text";
ddl.DataBind();
Good luck!
Example with existing properties:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "firstName";
bla.DataValueField = "emp_Id"
bla.DataBind();
I recommend this:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "fullName";
bla.DataValueField = "emp_Id"
bla.DataBind();
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string fullName get{ return firstName + " " + lastName;}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
Why don't you create a property called FullName to gets "FirstName + ' ' + LastName"? That would give you one field to deal with instead of two.
If you don't want or can't modify Employee, you may also try something along those lines:
var data = employee.Select (x =>
new KeyValuePair<int, string>(
x.emp_Id,
string.Format("{0}, {1}", x.lastName, x.firstName)
));
ddl.DataSource = data.ToList();
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();
This may also be useful if you have different pages with different dropdowns for employees, sometimes with Lastname first, sometimes with Firstname first, and maybe with and without a colon in between ...