سؤال

In my C# application I have a datagridview with 'person' data in it that means the datasource of this datagrisview is set with an IList of the class person.

My person model consists of the following fields (just the model, not the datagridview):

string foreName
string surname
int devisionId
int someOtherId
Organisation orga

Organisation is another model which is mapped as one-to-many with NHibernate. Among others organisation consists of the string:

string orgaName

Now comes the tricky part (for me).... In my datagridview I dont want to have all fields of person, I just want to have the following:

foreName
surname
orga.orgaName

Getting the first twoe fields is easy:

dataGridView.DataSource = listOfPersons.Select(x => new { ForeName = x.ForeName, SurName = x.Surname}).ToList();

This works fine so far but now I also want to have the name of the organisation within my datagridview so I tried this:

dataGridView.DataSource = listOfPersons.Select(x => new { ForeName = x.ForeName, SurName = x.Surname, OrganisationName = x.Organisation.organName}).ToList();

This would also work fine if every person has an organisation, but thats not the fact. Some persons do not have an organisation so 'Organisation' is null and trying to grab Organisation.organName ends with a nullpointerexeption.

The question now is: How can I write my select-statement for the datagridview-datasource so that the organisation name is shown when Organisation is not null, otherwisesomething else is printed to the datagridview (for example: no organisation available)

هل كانت مفيدة؟

المحلول

dataGridView.DataSource = listOfPersons.Select(x => new { ForeName = x.ForeName, SurName = x.Surname, OrganisationName = x.Organisation == null ? "None" : x.Organisation.organName}).ToList();

نصائح أخرى

Try this :

dataGridView.DataSource = listOfPersons.Select(x => new { ForeName = x.ForeName, SurName = x.Surname, OrganisationName = x.Organisation != null ? x.Organisation.organName : "No organisation available"}).ToList();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top