In my C# application I use NHibernate to get all rooms from my database table 'room'.
using (ISession pSession = NHibernateHelper.OpenSession())
{
IList<Room> roomList = pSession.QueryOver<Room>().
Where(x => x.FloorID == 3).
.List();
}
The table 'room' and also my Mapping class (Room.cs) contains lets say the following properties:
roomID
hash
date
identifier
I have a DataGridView which should display my table entries from the database: the code is:
roomDataGridView.DataSource = roomList;
That works fine so far. But now I decide that I dont want to show all the properties from the Room class, I only want to display
roomID
identifier
I tried the following:
roomDataGridView.DataSource = listOfRoomPropertiesForCurrentFloor.Select(x => new {x.Identifier, x.RoomID });
Unfortunately this does not work...nothing gets printed in my DataGridView.
Question: How can I store all properties from the room table in my room model BUT ONLY show TWO of the four properties in the DataGridView?
Make sure your column names are defined in the DataGridView and create the object, basically assign the x.Identifier to the name "Identifier" so it can be picked up and call the ToList() function
roomDataGridView.DataSource = listOfRoomPropertiesForCurrentFloor
.Select(x => new {Identifier = x.Identifier, RoomID = x.RoomID }).ToList();
Expecting that DataGridView attribute AutoCreateColumns should be set to true. There are already answers:
c# Hide a property in datagridview with datasource
Is there an Attribute I can use in my class to tell DataGridView not to create a column for it when bound to a List
Extract:
Mark the property which should not be displayed with an attribute [Browsable(false)]
Related
I have for the most part successfully connected to an API endpoint and manage to deserialize nested json result and bind it to a gridview using Newtonsoft.Json serialization attributes.
I however cannot bind to a dropdownlist. What is the correct property name to use to pass the supplier name to my dropdownlist?
I can see the property I want to pass (supplier name) and have tried all possible strings I can think of but all I get is the class name to display.
The Supplier Name displays fine on the gridview
I can see the property I want to display supplier -> name
Binding Code
var readdata = comsumeapi.Result;
if (readdata.IsSuccessStatusCode)
{
var displayrecords = readdata.Content.ReadAsAsync<IList<CoupaPODetails>>();
displayrecords.Wait();
empobj = displayrecords.Result;
GridView1.DataSource = empobj;
GridView1.DataBind();
DropDownList1.DataSource = empobj;
DropDownList1.DataTextField = "supplier";
DropDownList1.DataBind();
}
It would have been quite helpful to see your JSON object code but I think I can glean what I need from the screenshots
You've bound the drop down list to supplier object, not the name of the supplier. I think you should probably make a new list of all the different suppliers and bind to that, something like:
var x = empobj.Select(e => e.supplier.name).Distinct().ToList();
(Your supplier object only seems to contain a name? This a bit odd why there would even be a supplier object at all if it only houses a string. I figured it might contain more than that , like a name and an ID. If it contains more than that and you want a display text and a value that are different, use one of the techniques from here to group by eg the value and then linq .Select(g => new ListItem(){Text = g.First(), Value = g.Key}) to generate a List<ListItem> that can be the datasource for your drop down)
Don't forget that you'll also need to bind to the grid's row data bound event to set the selected item in the drop down, detail for which is here
I'd like to create a GridView (preferably telerik) where the columns are generated and bound based on rows in the database. The grid should look like this:
Here is an example of what the database setup is.
I have 3 database tables as follows:
Employees - A list of Employee Names
States- A list of States
EmployeeStates- join table, which has an EmployeeID, StateID, and boolean for checked or unchecked.
New rows can be added to both database tables so that the list of employees and list of cities will get longer.
How do I bound this to a GridView?
Don't know if you still have this issue, but we solved it a while back. It wasn't straightforward, but can be done. Our tables were for treatment sites (parts of the body) and treatment types, and we wanted to display a grid showing all the possible sites, along with the ones ticked for the patient in question.
The server-side query to get the data looked like this...
int systemID = 210;
var cross = TreatmentSites.Select(ts => new {
TreatmentSiteID = ts.ID,
TreatmentSiteName = ts.Description,
Checked = string
.Join("", TreatmentCheckTypes
.OrderBy(tct => tct.ID)
.Select(cs => SystemTreatmentSitesCheckeds
.Any(s => s.Active
&& s.SystemID == systemID
&& s.TreatmentSiteID == ts.ID
&& s.TreatmentCheckTypeID == cs.ID) ? "y" : "n"))
})
.ToArray();
This pulled out a list of sites, with a string of the form nnyyn for the types that were checked.
Nest job was to massage that into something that could be used by WPF. For that, we used the following code...
Dictionary<String, dynamic>[] data = new Dictionary<string, dynamic>[cross.Count()];
for (int crossN = 0; crossN < cross.Count(); crossN++) {
var d = new Dictionary<String, dynamic>();
d["TreatmentSiteID"] = cross[crossN].TreatmentSiteID;
d["TreatmentSiteName"] = cross[crossN].TreatmentSiteName;
for (int checktypeN = 0; checktypeN < treatmentCheckTypes.Count(); checktypeN++) {
d["C" + checktypeN] = cross[crossN].Checked[checktypeN] == 'y';
}
data[crossN] = d;
}
That gave us the data we needed. With that, the WPF view was able to add columns to the grid in code, then bind the data to the grid.
The above is the basic idea. More details of how it works can be found on my blog.
Hope that helps.
If you follow this link You should have enough examples to get some idea. Think points to the WPF telerik components.
You could set or bind the ItemsSource property of the RadGridView to an IEnumerable<YourType> where your YourType is a class that has the Employee, NJ, PA, RI and NY properties.
Or to a DataView of a DataTable.
You will have to write an SQL query that selects the appropriate data from the database and then create an instance of YourType for each returned record, or use the DataTable directly. There are plenty of example of how to communicate with a database available online: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx
I have a question which refers to whether it's possible to access another property in LINQ in order to set another property's value in LINQ:
var v = ctx.myTableItems
.Where(x => x.id== anotherid)
.Select(e => new MyViewModel
{
Title = e.Title,
CurrentPrice = e.CurrenctPrice.Value,
ItemID = e.ItemID.ToString(),
Transactions= e.Transactions,
Sales =
})
.Where(x=>x.Sales>0);
So check this out guys, when I was setting my Transactions property I set the transactions collection in my previous line, and now I'd like to set my sales propert with the Transactions property that was assigned in a previous line:
Transactions= e.Transactions,
Sales = e.Transactions.Sum(x=>x.Quantity) // Normaly I'd do it like this
But I wanted to try out something like this:
Sales = Transactions.Sum(x=>x.Quantity) // is this doable ?
So my question here is, is it possible to set another property within the select statement with a previously property's value? In my case it's Transactions collection ?
Is this doable, if so , how?
P.S. I'm trying to figure if this is doable because if I could use this previously set property's value , then I would avoid performing 2 unnecesary queries on my Transactions table in DB?
You cannot use the previous value because you dont want to call e.Transactions.Sum() for every item.
Just add a method to MyViewModel
public double GetSales()
{
return Transactions.Sum(x=>x.Quantity);
}
//at the end of your code use:
.Where(x=>x.GetSales()>0);
I have a DataSet with few tables, 2 of them are related in Conatraint in the XSD file.
When I save (update with the data adapter) the parent table I get this error:
Cannot make this change because constraints are enforced on relation XXX, and changing this value will strand child rows.
XXX is the relation in the XSD file.
I simply don't understand what is this, I've tried google but nothing.
The parent table id is connected with FK to a column in the child table and saving the parent table should update the child.
I don't understand this error, please help.
EDIT:
The code that creates new row in the child table MyDataSet.Patient_IVFOocytesFreezeOocytesInGroups:
// connect the oocytes with a group
IVFOocyteManagerDataset.Patient_IVFOocytesFreezeOocytesInGroupsRow newgrouprow = MyDataSet.Patient_IVFOocytesFreezeOocytesInGroups.NewPatient_IVFOocytesFreezeOocytesInGroupsRow();
if (selectedStraws.Count == 1)
{
int g = MyDataSet.Patient_IVFOocytesFreezeStraw.Where(x => x.IsSelecetd == true).Select(x => x.group_id).FirstOrDefault();
newgrouprow.group_id = MyDataSet.Patient_IVFOocytesFreezeGroups.Where(x => x.group_id == g).Select(x => x.group_id).SingleOrDefault();
OocyteStraws.Rows[i].StrawDisplayId = MyDataSet.Patient_IVFOocytesFreezeStraw.Where(x => x.IsSelecetd == true).Select(x => x.display_id).FirstOrDefault();
}
else
{
OocyteStraws.Rows[i].StrawDisplayId = -1;
newgrouprow.group_id = selectedStraws.Select(x => x.group_id).FirstOrDefault();
}
MyDataSet.Patient_IVFOocytesFreezeGroups is the parent table.
Well, after few hours I found the answer:
In the DataSet Designer, the reltaion wasn't Cascade. Tha'ts all.
Are you changing the ID value on the parent table or is it an auto generated identity? You really shouldn't be changing it in the update.
Can you post your data models and the updating code that you are using so that it is easier to see what is going on?
I´m having a problem, I retrieve all the Loans I have stored in my database like this:
list_loans = db.Loan.Where(x => x.State.id_state != 6).ToList();
db is the Object context.
Then, I assign that list as the DataSource for my DataGridView.
dgv_Loans.Datasource = list_loans;
With that info, I add some columns. Like for example, installments left to pay. I get that value by counting the result of a query.
The user can order the result using some options. Is easy to order the result from the fields that the entity have (using linq), but I dont know how to order the results using this new columns.
I read some posts here and tried this:
dgv_Loans.Sort(dgv_Loans.Columns["installments_left"], ListSortDirection.Ascending);
By doing this, I´m getting the following exception at runtime:
"DataGridView control must be bound to an IBindingList object to be sorted."
Is there anyway to use linq to orderby created columns in a DataGridViewColumn? Or how can I solve this error?
I know there are related posts, but after reading them, I can´t find a solution to this specific problem. Thats why I showed how I implemented to get some advice..
Rather than binding directly to the list retrieved from database, what I generally do is have a view class and have all the calculated properties in that class
public class LoanView : Loan {
public LoanView(Loan loan){
}
public int InsallmentsLeft { get { return ...; } }
}
and then bind the datasource to a list of this, this keeps sorting working.
Concerning about Sort datagridview by created columns using Entity Framework
I guess you need this Presenting the SortableBindingList<T>
Usage:
loanBindingSource.DataSource = new SortableBindingList<Loan>(list_loans.ToList());
dgv_Loans.Datasource = loanBindingSource;
int ID = Convert.ToInt32(cmbDepartments.SelectedValue);
var EmployeeList = from Employee in db.Employee
where Employee.DepartmentID == ID
select new
{
Employee.FirstName,
Employee.LastName
};
dataGridView1.DataSource = EmployeeList.ToList();
You could directly give the data source to dataGridView1.DataSource but you must write ToList() at the end of your query:
int ID = Convert.ToInt32(cmbDepartmanlar.SelectedValue);
dataGridView1.DataSource = (from Employee in db.Employee
where Employee.DepartmentID == ID
select new
{
Employee.FirstName,
Employee.LastName
}).ToList();