Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind object to textbox c#

I'm new to c# and I'm looking for a way to bind a property of an object of my own to the value of a textbox in a regular form (reset the property of the object everytime the value of the input changes).

I have read some information and it seems that this can be done only for database objects. Can you give me additional information.

like image 906
Lucia Avatar asked Sep 29 '10 22:09

Lucia


2 Answers

Assuming you mean Windows Forms textbox, say

textBox.DataBindings.Add("Text", obj, "SomeProperty");

whenever you feel like binding it. Bindings are usually done in Form_Load event handler, if the object can be obtained at that time of course, and if there's no complex logic with different data sources.

Note that this will only work in one direction (changing TextBox will yield object property changes). To sync the other way round, the object must implement INotifyPropertyChanged interface.

like image 71
Dan Abramov Avatar answered Oct 12 '22 11:10

Dan Abramov


If you want to persist the information between runs of the application (i.e. have it be saved when you close the app and re-appear when it opens), it's easiest to use the Windows Forms designer (I assume you are coding a WinForms app) to bind the value of the TextBox to an application setting. (This article on validation provides a screenshot similar to what you want.) (EDIT: Here is the exceptional article on the subject: Exploring Secrets of Persistent Application Settings. And here is a snippet page that I put together to discuss binding.)

This binding is automatically two-way, unlike the binding that @gaearon mentions. You just need to make sure that you save the settings (i.e. Properties.Settings.Default.Save()) before closing the application (e.g. as the event handler for the Form.Closing event).

If you need more clarification, leave a comment.

like image 44
Pat Avatar answered Oct 12 '22 11:10

Pat