I encountered a problem where I can't seem to make the names in the Combo Box appear once instead of multiple one. Is there anything in my codes that causes this problem? Any help will be greatly appreciated.
Below is the code to link the names to the combo Box.
private void Create_EmpDetails_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var viewEmpName = (from viewEN in Setupctx.employees
join ufi u in Setupctx.ufis on viewEN.UFISID equals u.UFISID
select new { u.EmployeeName , u.UFISID}).Distinct().ToList();
cbName.DataSource = viewEmpName;
cbName.DisplayMember = "EmployeeName";
cbName.ValueMember = "EmployeeName";
//cbName.ValueMember = "UFISID";
}
}
Each of those rows has a different UFISID, so Distinct() is not removing them.
It sounds like you just want to show employees:
cbName.DataSource = Setupctx.Employees;
I edited to my codes to this and I managed to show only 1 name for instead of multiple records.
private void Create_EmpDetails_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var viewEmpName = (from viewEN in Setupctx.employees
join ufi u in Setupctx.ufis on viewEN.UFISID equals u.UFISID
select new { u.EmployeeName }).Distinct().ToList();
cbName.DataSource = viewEmpName;
cbName.DisplayMember = "EmployeeName";
cbName.ValueMember = "EmployeeName";
//cbName.ValueMember = "UFISID";
}
}
Probably, it would be enough for you to replace
select new { u.EmployeeName , u.UFISID}
with
select new { u.EmployeeName }
in combobaxes we display the string as DisplayMember for users and id of members(maybe important for us) as ValueMember for us. more time we work with ids . my example :
class Country
{
public string Name { get; set; }
public int ID { get; set; }
public Country( int i,string s) { Name = s; ID = i; }
}
class ComboItem
{
public string DisplayMember { get; set; }
public int ValueMember { get; set; }
}
class ComboItemEqualityComparer : IEqualityComparer<ComboItem>
{
public bool Equals(ComboItem item1, ComboItem item2)
{
if (item1.ValueMember == item2.ValueMember && item1.DisplayMember == item2.DisplayMember)
{
return true;
}
return false;
}
public int GetHashCode(ComboItem item)
{
string str = item.DisplayMember + item.ValueMember;
return str.GetHashCode();
}
}
test :
List<Country> countries = new List<Country> {
new Country(1,"UK"),
new Country(2,"Turkey"),
new Country(8,"Turkey"),
new Country(5,"Turkey"),
new Country(2,"Turkey"),
new Country(3,"USA") ,
new Country(3,"USA")}; //.Distinct(new CountryEqualityComparer()).ToList();
var Data = (from i in countries
select new ComboItem { ValueMember = i.ID, DisplayMember = i.Name }).Distinct(new ComboItemEqualityComparer()).ToList();
cbName.DataSource = Data;
cbName.DisplayMember = "DisplayMember";
cbName.ValueMember = "ValueMember";
sometimes we have data that have displayname the same but the id of them arent. we can change the ComboItemEqualityComparer equals method to :
public bool Equals(ComboItem item1, ComboItem item2)
{
if (item1.ValueMember == item2.ValueMember )
{
return true;
}
return false;
}
enjoy.
for this question we can :
....
select new ComboItem { ValueMember = u.UFISID, DisplayMember = u.EmployeeName }).Distinct(new yourIEqualityComparer()).ToList();
Related
I work in Windows Forms. I have a combobox ('Departments' name) it contains a list of departments. By selecting a department in comboBox1(Staff), employees working in this department appear. But I can't select an employee, because they are not displayed
Code, filling in comboBox1(Staff). dataNames - dictionary(department name - array of employees)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (Departaments.SelectedItem != null)
{
this.Staff.Items.Clear();
var dataNames = DataForComdodox.ArrNames(Departaments.SelectedItem.ToString());
this.Staff.Items.AddRange(dataNames);
}
}
Code in Form1.Designer - comboBox1(Staff)
this.Staff.DrawMode = System.Windows.Forms.DrawMode.Normal;
this.Staff.FormattingEnabled = true;
this.Staff.Items.AddRange(new object[] {
});
this.Staff.Location = new System.Drawing.Point(374, 84);
this.Staff.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Staff.Name = "Staff";
this.Staff.Size = new System.Drawing.Size(158, 21);
this.Staff.TabIndex = 0;
this.Staff.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
I tried to change Staff.SelectedIndex = 0, after I fill comboBox1(Staff) with values, but in the end, when choosing a department, an employee was selected automatically with an index of 0
If var dataNames = DataForComdodox.ArrNames(xx) returns a list or array of class employees, you could override the ToString() in the employee class.
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
public override string ToString()
{
return $"{this.EmpId}: {this.EmpName}";
}
}
I am running into this error
cannot convert from 'System.Collections.Generic.List' to 'HWC.DataAccess.FAREmailList' HWC.DataAccess
I am not understanding this error because its the same list type
here is the method that I am using
public void PrepareToSendEmailFromFAR(int id)
{
HWC = new HWCEntities();
FileAReport far = HWC.FileAReports.Where(w => w.FileAReportID == id).FirstOrDefault();
List<FAREmailList> emailList = null;
if(far.DistrictID != 0)
{
emailList = new List<FAREmailList>();
var query = from dcx in HWC.DistrictContactXREFs
where
dcx.DistrictID == far.DistrictID
select new
{
dcx.ContactID,
dcx.Contact.ContactEmail,
dcx.Contact.ContactName
};
foreach(var a in query)
{
emailList.Add(new FAREmailList
{
ContactName = a.ContactName,
EmailAddress = a.ContactEmail
});
}
SendEmailFromFAR(emailList);
}
if(far.DistrictID == 0)
{
emailList = new List<FAREmailList>();
var query = from dcx in HWC.DistrictContactXREFs
join d in HWC.Districts on dcx.DistrictID equals d.DistrictID into d_join
from d in d_join.DefaultIfEmpty()
join sp in HWC.StateProvinces on new { StateProvinceID = d.StateID } equals new { StateProvinceID = sp.StateProvinceID }
where
d.StateID == far.StateCountyID
select new
{
dcx.ContactID,
dcx.Contact.ContactEmail,
dcx.Contact.ContactName
};
foreach (var a in query)
{
emailList.Add(new FAREmailList
{
ContactName = a.ContactName,
EmailAddress = a.ContactEmail
});
}
SendEmailFromFAR(emailList);
}
}
and here is the method thats receiving the emailList
public void SendEmailFromFAR(FAREmailList el)
{
}
the data class is
public class FAREmailList
{
public string ContactName { get; set; }
public string EmailAddress { get; set; }
}
the error is being thrown at
SendEmailFromFAR(emailList);
I am not seeing what the issue is, is it because this is all in the same class file?
The error makes sense to me. emailList is of type List<FAREmailList> and SendEmailFromFAR takes a FAREmailList as input.
public class School
{
public string Name { get; set; }
public bool Active { get; set; }
public int Children { get; set; }
}
public Func<string, object, object> someMethod = SomeMethod;
public static object SomeMethod(string name, object value)
{
return 1;
}
private void Form1_Load(object sender, EventArgs e)
{
List<School> ls = new List<School>();
School s = new School();
s.Name = "s1";
s.Active = true;
s.Children = 10;
ls.Add(s);
s = new School();
s.Name = "s2";
s.Active = false;
s.Children = 5;
ls.Add(s);
IEnumerable<object> rows = ls;
var result = rows.Select(
x => x.GetType().GetProperties().Select(p => someMethod(p.Name, p.GetValue(x, null))));
}
Note:
rows can be anything
The result should like this:
Name Active Children New_Column
s1 true 10 ?? for example if active=true then display Ok
I have the below class and linq query I am using to populate a grid!
The Title is the same for every row returned. What I am trying to do is populate mString with the distinct Title from the query so I can bind it to a seperate textblock.
I probably didnt need to show all the code, but maybe it will help. How can I show the distinct Title.
public class Items
{
public int Id { get; set; }
public string Details { get; set; }
public string Title { get; set; }
public int NewNumber { get; set; }
}
private ObservableCollection<Items> mItem = new ObservableCollection<Items>();
private string mString = string.Empty;
public string SpecTitle
{
get { return mString; }
}
public ObservableCollection<Items> GetItems
{
get { return mItem; }
}
Here is the linq query
var results = (from z in mContext.View
orderby z.ItemNumber ascending
where z.ItemId == mId
select new Items()
{
Id = z.ItemId,
Details = z.Details,
Title = z.ItemTitle,
NewNumber = z.ItemNumber
});
List<Items> mNewItems = results.ToList();
mItem.Clear();
mNewItems.ForEach(y => mItem.Add(y));
var titleList = mNewItems.Select(i => i.Title).Distinct().ToList();
Converting my comment into an answer:
just do Items.Select(x => x.Title).Distinct();.
There is an additional library called moreLinq https://code.google.com/p/morelinq/ that has an extenction distinctby that you can you to distinct based on the given key.
it would as simle as this
var results = (from z in mContext.View
orderby z.ItemNumber ascending
where z.ItemId == mId
select new Items()
{
Id = z.ItemId,
Details = z.Details,
Title = z.ItemTitle,
NewNumber = z.ItemNumber
}).DistinctBy(c=>c.Title).ToList();
You can implement your custom comparer for distinct:
public class ItemsComparer : IEqualityComparer<Items>
{
public bool Equals(Items x, Items y)
{
return x.Title == y.Title;
}
public int GetHashCode(Items obj)
{
return obj.Title.GetHashCode();
}
}
then just use
var titleList = mNewItems.Distinct(new ItemsComparer()).Select(t=>t.Items);
Looking for an example where I can filter my collection based on some filtering criteria.
I have been looking for some example where given a list /array i can filter a collection.
In the example below in my find method I am trying to filter based on 2 values ,looking for something like an "IN" function any suggestions?
class Program
{
static void Main()
{
//Print all customres that belong to below deparments and match on surname
var criteria=new Criteria
{
Departments = new List<string> {"BusinessAnalyst", "Account"},
Surname = "Bloggs"
};
List<Customer> customers = Repository.Find(criteria);
customers.ForEach(x => Console.WriteLine(string.Format("Surname: {0} Department :{1}", x.Surname,x.Department)));
Console.Read();
}
}
public class Repository
{
public static List<Customer>GetCustomers()
{
return new List<Customer>
{
new Customer { Name = "Jon",Surname="Smith",Department = DepartmentType.Managers},
new Customer{Name = "Bill",Surname = "Gates",Department = DepartmentType.Managers},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Developers},
new Customer { Name = "Mark",Surname="Boo",Department = DepartmentType.Account},
new Customer{Name = "Ron",Surname = "Scott",Department = DepartmentType.Managers},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Developers},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.BusinessAnalyst},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Account},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Account},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.Managers}
};
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer>customers=Repository.GetCustomers();
//Filter on departments
//ERROR HERE AS I cannot do this "IN" would be fantastic.
customers = customers.Contains(criteria.Departments);
//now filter on name
customers = customers.Where(x => x.Surname == criteria.Surname).ToList();
return customers;
}
}
public enum DepartmentType
{
Account,
Managers,
Developers,
BusinessAnalyst
}
public class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
public DepartmentType Department { get; set; }
}
public class Criteria
{
public Criteria()
{
Departments=new List<string>();
}
public string Name { get; set; }
public string Surname { get; set; }
public List<string> Departments { get; set; }
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department.ToString()));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
But considering you use an enum for the Department (DepartmentType), shouldn't your Criteria class use the same instead of a string?
If you define the criteria.Departments as List<DepartmentType> then you can write
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
Contains returns a bool defining whether a specified object is contained in a collection. Based on your example, you will need to use Where to filter the customers, then use Contains on the departments:
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
i think you want something like this..
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
You want
Customers.Where(c => criteria.Departments.Contains(c.Department.ToString()))
Not sure if this is what you're looking for but the following:
List<Customer> FilteredCustomers = (from c in customers where Criteria.Departments.Contains(c.deparment) && c.surname == Criteria.Surname select c).ToList();
Would equate to something like this in SQL:
SELECT *
FROM Customers
WHERE Department IN (
List of departments
)
AND Surname = surname
I haven't tested this but I think it should work and bring back what you want.