Binding two lists into one data grid view - c#

So I have two lists (Members and RealEstate)
I want my DataGridView to display results of the MemberID that was written in a text box I have.
Results include:
MemberID, FirstName from the Members List and
EstateType, EstatePrice, EstateArea from the RealEstate List
My code is as follows :
List<Members> member = FrmSell.MembersList.FindAll(owner => owner.MemberID == int.Parse(FrmSell.txt));
List<RealEstate> realestate = FrmSell.EstateList;
dgvProperty.DataSource = member;
dgvProperty.DataSource = realestate;
And when I click on my button it only displays the results from the second list which is the RealEstate list and not the first one, I want to display results from both lists combined into a single data grid view.
If you need any more clarification please do tell me.
Sample data from the list :
//Sample data
Members m1 = new Members(001,"Ahmed","Muhairy",503299999);
MembersList.Add(new Members(002,"Khalfan","AlMarri",502344556));
RealEstate r1 = new RealEstate("Villa",35000,"Quoz",4,2);
EstateList.Add(new RealEstate("House",55000,"Sharjah",6,4));

You will need to combine the fields from the matching entries in the two lists into either a DataSet or DataTable, or into a list of items of a new class that contains the fields from both input types.
For this to work, there must be a field in either the Member or RealEstate class that allows matching up the entries from both input lists.
As an example, I am going to assume the following: your RealEstate class has an OwnerID field, whose value identifies one of the members in the MembersList, because it is equal to the member's MemberID value.
Now you can do the following:
// This combines the fields from Member and RealEstate
// for a row to be displayed in the data grid.
public class MemberRealEstate
{
public int MemberID { get; set; }
public string MemberName { get; set; }
public int EstateID { get; set; }
public string EstateType { get; set; }
public double EstatePrice { get; set; }
public string EstateArea { get; set; }
}
And create a new list, combining entries from the other two:
var forMemberId = int.Parse(FrmSell.txt);
var memberRealEstateList =
(from estate in FrmSell.EstateList
from member in FrmSell.MembersList
where member.MemberID == forMemberId && member.MemberID == estate.OwnerID
select new MemberRealEstate() {
MemberID = member.MemberID,
MemberName = member.FirstName + " " + member.LastName,
EstateID = estate.EstateID,
EstateType = estate.EstateType,
EstatePrice = estate.EstatePrice,
EstateArea = estate.EstateArea
}).ToList();
Now you can assign this list as the DataSource for your DataGridView:
dgvProperty.DataSource = memberRealEstateList;

Related

How to set DataGridView column header through a linq query?

I have an sql database for vehicle details. I want to display some fields of the linq query on a datagridview control with different column headers with spaces other than the database field names. I tried it as below but it gives an error. How do I do this?. Thank you guys.
var vlist = from lst in dc.tblVhcleInfos
select new {"Registration Number"= lst.RegNo, "Make and Model"=lst.makeModel, "Year of Manufacture"=lst.YOM};
dataGridView1.DataSource = vlist;
You cannot set up Custom names for Dynamic LINQ Classes, declare class first, add DisplayName attribute to properties, like this
// Define new Class
public class VhcleInfo
{
[DisplayName("Registration Number")
public string RegNo { get; set; }
[DisplayName("Make and Model")
public string MakeModel {get; set; }
[DisplayName("Year of Manufacture")
public int Year { get; set; }
}
// Create IEnum for Defined Class
var vlist = from lst in dc.tblVhcleInfos
select new VhcleInfo() { RegNo = lst.RegNo, MakeModel = lst.makeModel, Year = lst.YOM };
// Set Data Source
dataGridView1.DataSource = vlist;

Binding Complex Data source of a class into Grid View

Here I have these Classes:
public class CustomerDebt
{
public int ID { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Remain { get; set; }
public List<Shops> details = new List<Shops>();
}
public class Shops
{
public List<int> ints = new List<int>();
public List<string> strings = new List<string>();
}
I'm making a list of CustomerDebts objects:
List<CustomerDebt> debts = new List<CustomerDebt>();
and Here I will add one item to it:
Shops shop = new Shops();
shop.ints.Add(1);
shop.ints.Add(2);
shop.strings.Add("M");
shop.strings.Add("S");
shop.strings.Add("F");
CustomerDebt d = new CustomerDebt();
d.ID = 12;
d.Name = "Joe";
d.Family = "Steven";
d.Remain = "1000";
d.details.Add(shop);
debts.Add(d);
Now I bind debts list into a grid view:
gridview.DataSource = debts;
It will automatically fill the grid view with only "ID,Name,Family,Remain" properties of CustomerDebt Class. But I need to bind the List property which is a list of another Class into grid view.
I think it needs something like {get; set;} to be shown in grid, But also I do not know If the grid can show a nested class like this.
Hope I'm clear. What should I do to get a clean Grid view with such list of Class objects?
There is no built-in support for Master Details in the DataGridView Control in Windows Forms. But we have the option to use Third Party Libraries Like:
Telerik.
Devexpress.
As for the binding issue, yes you need to have a public property with a public getter:
public List<Shops> details { set; get; } = new List<Shops>();
For prior to C# 6 you can use:
public class CustomerDebt
{
public CustomerDebt()
{
details = new List<Shops>();
}
public List<Shops> details { set; get; }
}
Another way of doing this other than the accepted answer can be like below. Columns can be added manually and then the rows can be filled accordingly.
this.gridview.Columns.Add("ID", "ID");
this.gridview.Columns.Add("Name", "Name");
this.gridview.Columns.Add("Family", "Family");
this.gridview.Columns.Add("Remain", "Remain");
this.gridview.Columns.Add("Details", "Details");
foreach (var debt in debts)
foreach (var detail in debt.details)
this.dataGridView1.Rows.Add(debt.ID, debt.Name, debt.Family, debt.Remain, "Ints:" + string.Join(",", detail.ints) + " Strings:" + string.Join(",", detail.strings));

Remove columns from list object out of a class c#

I need the possiblity to create Code in C# like this
public class SummaryA
{
public string name { get; set; }
public string surename { get: set; }
public int age { get; set;}
}
now I create an list object from the class SummaryA
List<SummaryA> list1= new List<SummaryA>();
yet I need the possibility to remove the column age from the list Summary, anyone have ideas?
I need this for some more columns, so I wish the list was dynamically or some things else.
sry for my bad english.
To completely remove the column you really need another class to store the data in, for example:
public class AgelessSummaryA
{
public string name { get; set; }
public string surename { get: set; }
}
And now you can project the first list into a new list of this class with Linq and Select:
List<AgelessSummaryA> agelessSummaries = ageSummaries
.Select(s => new AgelessSummaryA
{
name = s.name,
surename = s.surename
})
.ToList();
To use it for in a grid or for some display i guess, then you can use anonymous types where you can shape the data the way you like:
var projectedList = (from l in list1
select new
{
name = l.name,
surename = l.surename
}).ToList();

Getting value and putting value to combobox

I'm newbie with winforms and I'm using a combobox. I like to learn how to load from Database to Controls (Combobox) and how to SAVE values from Control (combobox) to Database field.
Below I need some help on process get from Combobox and put/select value to combobox... But don't know how to do...
Below I get all rows in a list and bind to a combobox. That works fine, but like to do some actions which I'm struggling.
Can someone advice how to do these action?
I'd like to "add on top" of comboboxList an empty value so they can also select an empty value in comboboxlist.
How to select a value in combobox when putting from DB to Control.. I'm doing like this
comboboxAccount.SeletedText = _account.Number, but it's not selecting.
now it's showing "Number" in combobox, but I like to show Number + "-" Description. How to do this? now it's showin e.g. 4000 but I like to show "4000 - Description1"
I like to store the Account.Id into the Database not the Account.Number, but how can I do that because the combobox is showing the Number... so SelectedText is not which I want.
Code:
public class Account
{
public Int32 Id { get; set; } e.g. 1
public string Number{ get; set; } e.g. 4000 (alpha-numeric)
public string Description1 { get; set; } e.g. Customer
public string Description2 {get; set;} e.g. VAT account
public string Language {get; set;} e.g. EN
}
//returns all rows
IList<Account> _account = new List<Account>(Account_repository.GetAll());
comboboxAccount.DataSource = account;
comboboxAccount.DisplayMember = "Number";
comboboxAccount.Add(??); (see point 1)
//saving to database
Client _client = new Client();
_client.Account = comboboxAccount.??; (see point 4)
1) I'd like to "add on top" of comboboxList an empty value so they can
also select an empty value in comboboxlist.
An item can never be added directly to the comobbox items, if the DataSource property is set.
So, the list(datasource) should be updated with empyt/dummy object before setting it as the DataSource.
You might have to find a way to describe that your current object is a dummy object.
Example, you could introduce an EmptyItem property, and handle/filter it before saving:
public class Account
{
public Account(bool isEmptyItem =false)
{
this.EmptyItem = isEmptyItem;
}
public Int32 Id { get; set; }
public string Number { get; set; }
public string Description1 { get; set; }
public string Description2 { get; set; }
public string Language { get; set; }
public bool EmptyItem { get; private set; }
}
IList<Account> _account = new List<Account>();
_account.Add(new Account(true))
_account.AddRange(Account_repository.GetAll());
.
2) *How to select a value in combobox when putting from DB to Control..I'm doing like this comboboxAccount.SeletedText = _account.Number, but it's not selecting.*
Since the comboBox is binded to an object, you cannot set its SelectedText instead you should use SelectedItem
Example://You need to write a logic to find out how to get this item.
this.comboboxAccount.SelectedItem = this.comboboxAccount.Items[1];
3) now it's showing "Number" in combobox, but I like to show Number + "-"
Description. How to do this? now it's showin e.g. 4000 but I like to
show "4000 - Description1"
You might have to expose another propety say DisplayText and bind it to DisplayMember of the combobox.
Example:
public class Account
{
public string Number { get; set; }
public string Description1 { get; set; }
public bool EmptyItem { get; private set; }
public string DisplayText
{
get{return this.Number + "-" + this.Description1}
}
}
this.comboboxAccount.DisplayMember = "DisplayText";
4) I like to store the Account.Id into the Database not the
Account.Number, but how can I do that because the combobox is showing
the Number... so SelectedText is not which I want.
You should use SelectedItem since you have binded an object
var account = this.comboboxAccount.SelectedItem as Account;
var accountID = account.Id;
First, I think you shoul use something like a Dictionary or List> or DataTable.
1) You should insert your empty value in your List and then bind it to your combobox
_account.Insert(0, "Empty");
2) Define your ValueMember also(you shoul have a List or a DataTable):
If you have a DataTabele:
comboboxAccount.ValueMember = "columnID";
comboboxAccount.DisplayMember = "columnValue";
comboboxAccount.DataSource = yourDataTable;
combobox.SelectedIndex = 0; //your empty value
3) You should create another property in your class and use this as DisplayMember;
string NumberDescription{ get; set; };
comboboxAccount.DisplayMember = "NumberDescription";
4) If you want to store the ID of the selected value you should use your previously defined ValueMember(the column ID):
int value = Convert.ToInt32(cbomboboxAccount.SelectedValue);
// if you want to save the text of the value selected in the combobox:
string strValue = comboboxAccount.Text;

DataGridView not displaying values using LINQ

It's very simple for the user.
They select the type of part, manufacturer from a ComboBox, and search the part code in a text box. Click search and the results return in a DataGridView.
Code:
var mType = CmbType.SelectedItem.ToString();
var mManufacturer = CmbMfr.SelectedValue.ToString();
var mCode = Convert.ToString(TxtProductCode.Text);
switch (mType)
{
case "Faucets":
var faucets = Resources.Accessor.SearchFaucets(mManufacturer, mCode);
DgInventory.DataSource = faucets;
break;
case "Parts":
var parts = Resources.Accessor.SearchParts(mManufacturer, mCode);
DgInventory.DataSource = parts;
break;
}
Accessor Code:
public static List<TblFaucets> SearchFaucets(string mId, string mCode)
{
var dataConnect = new PxLinqSqlDataContext();
return (from f in dataConnect.GetTable<TblFaucets>()
where (f.Mfr == Convert.ToInt32(mId))
where (f.Code == mCode)
select f).ToList<TblFaucets>();
}
What "messes up" is the results:
ID: correct
Mfr: is the ID from its table, not the name
Code: Correct
Description: correct
Price: correct
Date: correct
Manufacturer: I don't know why this is even here, its result is "PXDB.TblManufacturers
First, PXDB.TblManufacturers seems to be a relation from tblFaucets to tblManufactureres.
Mfr seems to be the foreignKey value within your faucets table refering to a manufacturer.
You may try creating an anonymous type holding only those data you want to. Within your select clause pick your data - as well as any relational data.
public static List<DisplayFaucet> SearchFaucets(string mId, string mCode)
{
var dataConnect = new PxLinqSqlDataContext();
return (from f in dataConnect.GetTable<TblFaucets>()
where (f.Mfr == Convert.ToInt32(mId))
where (f.Code == mCode)
select new DisplayFaucet () { // create anonymous object
ID = f.ID, // only holding the data you want to
Manufacturer = Manufacturer.Name, // assuming there is property Name within your manufacturer table?!
Code = f.Code,
Description = f.Description,
Price = f.Price,
Date = f.Date
}).ToList();
}
Add another class to hold your data to display
public class DisplayFaucet
{
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Code { get; set; } // check type
public string Description { get; set; }
public doublePrice{ get; set; } // check type
public DaetTime Date { get; set; } // check type
}
Note that SearchFaucets(..) may no longer return items of type tblFaucet! Instead I created a new class. This one contains all data which should be displayed!

Categories

Resources