Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 309
Tom_Lee2010 Avatar asked Oct 14 '10 16:10

Tom_Lee2010


2 Answers

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);
    }
like image 60
SKG Avatar answered Oct 25 '22 03:10

SKG


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"; }}
}
like image 35
Morfildur Avatar answered Oct 25 '22 04:10

Morfildur