O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Data Binding

Earlier, we configured a data source and then we added some controls to represent our data. Now it’s time to connect the two. If we select the text box for the title, and then in the Properties panel scroll to the top of the list, there’s an expandable (DataBindings) item, inside which is a list of properties you’re likely to want to bind. (You can bind other properties, but most controls have only a handful of properties that it’s likely to be useful to data-bind to.) If you show the drop down for the Text property, the reason for adding a binding source earlier becomes apparent. As Figure 22-9 shows, Visual Studio offers a list of available data sources (just the one here—our form’s entriesSource), which you can expand to select the property you require.

We’ll bind the two text boxes and date picker (binding the Value property in that case) on our form to the three properties. To check that this is working, we’ll need some data—the list we created earlier is currently empty. We’ll add a helper function to create a new item; we’ll need this for when the user clicks the New button, as well as for creating an initial item for when the application starts:

private void CreateNewItem()
{
    ToDoEntry newEntry = (ToDoEntry) entriesSource.AddNew();
    newEntry.Title = "New entry";
    newEntry.DueDate = DateTime.Now;
    entriesSource.ResetCurrentItem();
}

Notice that we’re using the AddNew method offered by the binding source—this means the binding system is aware that a new item is being ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required