7

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.

2
  • Is this in winforms or asp.net? Are you wanting it to be live binding (so as soon as something changes on the server it changes on the form) or are you wanting to load the value at the user request? Do you want database binding or something else? You are aware that textbox.text is text (string), not object, right? Commented Sep 29, 2010 at 22:14
  • 1
    Thanks Drachenstern, Gaeraron has given me the answer I was looking for. Commented Sep 29, 2010 at 22:25

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.