简体   繁体   中英

How to bind Navigation Property (second level model's two properties) in DataGridView's single column using BindingSource?

I have faced problem to show the values in grid view using binding source. I have two models as Company and Partners .

  1. I have PartnerId in Company Model,
  2. and Partner model has 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM