views:

52

answers:

2

Hey all,

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.

+1  A: 

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"; }}
}
dbemerlin
It wasn't what I was looking for, but thanks anyway!
Tom_Lee2010
+4  A: 

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);
    }
SKG
+1 I have used this exact solution in a project of mine
Scott Chamberlain
Yep, just tried it and works like a charm. THANKS! (can't add a score, because I'm a newbie on this form... Oh well, next time)
Tom_Lee2010
You can mark it as an answer though :-)
SKG
Sheez, who would've guessed the transparent check item to be the thing to click... Thanks again SKG!
Tom_Lee2010