Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How does formatting work with data binding?

Windows Forms binding supports formatting of the target data using .NET framework format strings.  For example, when binding a Decimal property on a business object (e.g. Order.Total) to a string property on a Control (e.g. TextBox.Text) a format string (e.g. "c") can be specified such that the value is displayed as a locale dependent currency value (e.g. $1.10).  Windows Forms leverages IFormattable for string formatting.

In addition to standard format strings, simple binding provides an eventing model that allows developers to plug in their own custom formatting (Binding.Format event) and parsing (Binding.Parse event) logic.

/*******************************************************************
* Setup (using the Visual Studio Form designer):
* 
*  Add 2 TextBoxes to the Form (textBox1 and textBox2)
*  Add the code below to the Form.Load event
******************************************************************/

/*******************************************************************
* Data Source setup:
* 
* Create a Table named Numbers and add 3 columns
*  ID:     int
*  Name:   string
*  Cost:   Decimal
******************************************************************/

DataTable _dt;

_dt = new DataTable("Numbers");

_dt.Columns.Add("ID", typeof(int));
_dt.Columns.Add("Name", typeof(string));
_dt.Columns.Add("Cost", typeof(decimal));

_dt.Rows.Add(0, "Zero", 10.0M);
_dt.Rows.Add(1, "One", 11.1M);
_dt.Rows.Add(2, "Two", 12.2M);

/*******************************************************************
* Bind TextBox.Text (string) to Numbers.ID (integer)
* The binding runtime will handle type conversion between integer
* and string
******************************************************************/
       
this.textBox1.DataBindings.Add("Text", _dt, "ID", true);

/*******************************************************************
* Bind TextBox.Text (string) to Numbers.Cost
* The binding runtime will display the value as Currency ($value.00)
*
* Note that this manually creates and adds the Binding to the
* control’s DataBinding collection rather than using the
* DataBindings.Add overload.
******************************************************************/

Binding cb = new Binding("Text", _dt, "Cost", true);

/* .NET Framework Currency format string */
cb.FormatString = "c";

/* Add the binding to the Textbox */
this.textBox2.DataBindings.Add(cb);


Page view counter