Niiw Niiw - 5 days ago 6
C# Question

Join two string properties (firstName + lastName) of usercontrol and assign it to label

I made a custom usercontrol which contains a label.
I have 3 string properties : firstName, lastName, fullName.

How can I set the label's text = FullName ?

public string firstName
{
get; set;
}

public string lastName
{
get; set;
}

public string fullName //this fails
{

get { return string.Format("{0} {1}", firstName, lastName); }
set { labelFullName.Text = value; }
}

Answer

Looks like Windows Form to me. In WPF you would be using labelFullName.Content property. Assuming you want to set the label as the fullname each time first name or last name changes, then one option would be to do this within your UserControl class:

private String _sFirstName = "";
private String _sLastName = "";

public String FirstName { 
  get { return _sFirstName; }
  set { _sFirstName = value; UpdateLabel(); }
}
public String LastName { 
  get { return _sLastName; }
  set { _sLastName = value; UpdateLabel(); }
}
public String FullName {
  get { return _sFirstName + " " + _sLastName; }
}
private void UpdateLabel() {
  // do within a UI thread to prevent threading issues
  this.BeginInvoke((Action)(() => {
    labelFullName.Text = this.FullName.Trim();
  }));
}
Comments