Experienced Windows programmers must be familiar with writing code from a control and storing values on a control:
public Form1 : Form
{
private MyType myDataValue;
private TextBox textBoxName;
private void InitializeComponent( )
{
textBoxName.Text = myDataValue.Name;
this.textBoxName.Leave += new
System.EventHandler( this.OnLeave );
}
private void OnLeave( object sender, System.EventArgs e )
{
myDataValue.Name = textBoxName.Text;
}
}
It's too easy, as you know, to repeat the code. The reason for not liking this kind of repetitive code is that there should be a better way. Yes. NET Framework supports data binding, which maps the properties of an object to the properties of the control:
textBoxName.DataBindings.Add ( "Text",myDataValue, "Name" );
The code above will bind the Textboxname control's "Text" property to the Mydatavalue object's "Name" property. Internally there are two objects, binding management (Bindingmanager) and Flow Management (CurrencyManager), which implements the transfer between the control and the data source. You've probably seen examples of structures, especially between datasets and DataGrid. You may also have done some examples of data binding. You are likely to simply use the functionality that is obtained from data binding on the surface. You can avoid writing duplicate code with efficient data binding.
A complete approach to data binding may take at least one book to illustrate, or two. Both Windows applications and Web applications support data binding. Rather than writing a complete data-binding argument, I do want you to remember the core benefits of data binding. First, using data binding is much simpler than writing your own code. Second, you should use it as much as possible when you are displaying the text elements through attributes, which can be well bound. Third, in Windows Forms, you can synchronize data that is bound to multiple controls to detect related data sources.
For example, suppose you want to display text as red when the data is not valid, and you might write code like this:
if ( src.TextIsInvalid )
{
textBox1.ForeColor = Color.Red;
} else
{
textBox1.ForeColor = Color.Black;
}
This is good, but you have to call this code at any time when the text source changes. This may be when the user edits the text, or when the underlying data source changes. There are so many things to deal with, and there are a lot of places you might miss. However, when using data binding, adding an attribute to the SRC object returns the appropriate foreground color.
Another logic might be to set values that can change to the appropriate color based on the state of the text message:
private Color _clr = Color.Black;
public Color ForegroundColor
{
get
{
return _clr;
}
}
private string _txtToDisplay;
public string Text
{
get
{
return _txtToDisplay;
}
set
{
_txtToDisplay = value;
UpdateDisplayColor( IsTextValid( ) );
}
}
private void UpdateDisplayColor( bool bValid )
{
_clr = ( bValid ) ? Color.Black : Color.Red;
}