Databinding a label in C# with additional text?
Solution 1
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);
}
Solution 2
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"; }}
}
Tom_Lee2010
Updated on June 14, 2022Comments
-
Tom_Lee2010 about 2 years
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.
-
Tom_Lee2010 over 13 yearsYep, 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 over 13 yearsSheez, who would've guessed the transparent check item to be the thing to click... Thanks again SKG!
-
Stavros about 12 yearsThanks for the answer. How do you make sure that you save only the databoundColumnText, without the "Custom text"?