I have faced problem to show the values in grid view using binding source. I have two models as Company
and Partners
.
PartnerId
in Company Model, FirstName
and LastName
. I have showed the company info and partner's first name as shown above.
Now, I need to show both partner's first name and last name in single column as PartnerName
. Could any one help me resolve this?
Option 1 - CellFormatting
As an option you can use CellFormatting
event of DataGridView
and show desired value:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//I Suppose you want to show full name in column at index 3
if(e.RowIndex>=0 && e.ColumnIndex==3)
{
var company = (Company)(this.dataGridView1.Rows[e.RowIndex].DataBoundItem);
if (company != null && company.Partner != null)
e.Value = string.Format("{0} {1}", company.Partner.FirstName,
company.Partner.LastName);
}
}
Option 2 - ToString()
As another option you can override ToString()
method of Partner
class and show the Partner
in a column:
public override string ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
Make property which returns formated full name and bind this one to grid cell. You could use multibinding but that needs additional converter which returns (as your additional property) formated string - for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.