3

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?

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44

2 Answers2

3

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);
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0

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.

  • could you please give any example for this? – Balagurunathan Marimuthu Apr 21 '16 at 06:37
  • In your model class: private string FirstName; private string LastName; public string FullName { get { if (!string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName)) return string.Format("{0} {1}", FirstName, LastName); else return string.Empty; } } And you bind FullName instead of FirstName/LastName – Elektryczny Apr 21 '16 at 06:44