Programming Microsoft ASP.NET 4 - Dino Esposito [220]
var data = new DataSet();
var adapter = new SqlDataAdapter(commandText, connectionString);
adapter.Fill(data);
// Table is the default name of the first table in a
// DataSet filled by an adapter
grid.DataMember = "Table";
grid.DataSource = data;
grid.DataBind();
DataMember and DataSource can be set in any order, provided that both are set before DataBind is invoked. DataMember has no relevance if you bind to data using DataSourceID with standard data source components.
The DataTextField Property
Typically used by list controls, the DataTextField property specifies which property of a data-bound item should be used to define the display text of the nth element in a list control:
public virtual string DataTextField {get; set;}
For example, for a drop-down list control the property feeds the displayed text of each item in the list. The following code creates the control shown in Figure 10-2:
CountryList.DataSource = data;
CountryList.DataTextField = "country";
CountryList.DataBind();
Figure 10-2. A drop-down list control filled with the country column of a database table.
An analogous behavior can be observed for other list controls, such as ListBox and CheckBoxList.
Note
List controls can automatically format the content of the field bound through the DataTextField property. The format expression is indicated via the DataTextFormatString property.
The DataValueField Property
Similar to DataTextField, the DataValueField property specifies which property of a data-bound item should be used to identify the nth element in a list control:
public virtual string DataValueField {get; set;}
To understand the role of this property, consider the markup generated for a drop-down list, set as in the code snippet shown previously:
The text of each