Tom_Lee2010
Tom_Lee2010

Reputation: 83

Databinding a label in C# with additional text?

Is there an easy way to databind a label AND include some custom text?

Of course I can bind a label like so:

someLabel.DataBindings.Add(new Binding("Text", this.someBindingSource, "SomeColumn", true));

But how would I add custom text, so that the result would be something like: someLabel.Text = "Custom text " + databoundColumnText;

Do I really have to resort to custom code...?

(maybe my head is too fogged from my cold and I can't see a simple solution?)

TIA for any help on this matter.

Upvotes: 8

Views: 12592

Answers (2)

SKG
SKG

Reputation: 1462

You can always use Binding.Format event.

http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx

The Format event is raised when data is pushed from the data source into the control. You can handle the Format event to convert unformatted data from the data source into formatted data for display.

Something like...

    private string _bindToValue = "Value from DataSource";
    private string _customText = "Some Custom Text: ";
    private void Form1_Load(object sender, EventArgs e)
    {
        var binding = new Binding("Text",_bindToValue,null);
        binding.Format += delegate(object sentFrom, ConvertEventArgs convertEventArgs)
                              {
                                  convertEventArgs.Value = _customText + convertEventArgs.Value;
                              };

        label1.DataBindings.Add(binding);
    }

Upvotes: 15

user253984
user253984

Reputation:

I don't know of any simple way, but what should work is a derived class with an extra property that returns the modified Text.

class FooAppendedText : FooText
{
  public String AppendedText { get { return this.Text + " xyz"; }}
}

Upvotes: 1

Related Questions