DataGrid.AutoGenerateColumns Property
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Gets or sets a value that indicates whether the columns are created automatically.
public:
property bool AutoGenerateColumns { bool get(); void set(bool value); };
public bool AutoGenerateColumns { get; set; }
member this.AutoGenerateColumns : bool with get, set
Public Property AutoGenerateColumns As Boolean
Property Value
true
if columns are created automatically; otherwise, false
. The registered default is true
. For more information about what can influence the value, see DependencyProperty.
Examples
The following example shows how to auto-generate columns and change the columns at creation time in the AutoGeneratingColumn event handler.
<!-- The DataGrid.DataContext is a DataTable that contains a list of customers. The DataTable columns are
Title, FirstName, MiddleName, LastName, Suffix, CompanyName, EmailAddress, and Phone.-->
<DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="DG1_AutoGeneratingColumn" />
//Access and update columns during autogeneration
private void DG1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
string headername = e.Column.Header.ToString();
//Cancel the column you don't want to generate
if (headername == "MiddleName")
{
e.Cancel = true;
}
//update column details when generating
if (headername == "FirstName")
{
e.Column.Header = "First Name";
}
else if (headername == "LastName")
{
e.Column.Header = "Last Name";
}
else if (headername == "EmailAddress")
{
e.Column.Header = "Email";
}
}
'Access and update columns during autogeneration
Private Sub DG1_AutoGeneratingColumn(ByVal sender As Object, ByVal e As DataGridAutoGeneratingColumnEventArgs)
Dim headername As String = e.Column.Header.ToString()
'Cancel the column you don't want to generate
If headername = "MiddleName" Then
e.Cancel = True
End If
'update column details when generating
If headername = "FirstName" Then
e.Column.Header = "First Name"
ElseIf headername = "LastName" Then
e.Column.Header = "Last Name"
ElseIf headername = "EmailAddress" Then
e.Column.Header = "Email"
End If
End Sub
Remarks
Setting AutoGenerateColumns to true
or false
creates or removes auto-generated columns. When the AutoGenerateColumns property is set to true
, the AutoGeneratingColumn event will be raised for each column that is created. You can change or cancel the column being created in the AutoGeneratingColumn event handler.
When auto-generation of all columns is complete, the AutoGeneratedColumns event is raised.
Note
DataGrid cannot auto-generate columns when the source is XML data. In this case, create a custom Columns collection. For an example, see DataGridTextColumn.