简体   繁体   中英

DataGrid AutoGenerateColumns=“True” - how to append one extra column?

I'm using DataGrid with AutoGenerateColumns="True". Now in addition to auto-generated columns I want to add one my "custom" column, so called "service" column. (in it I want to have several hyperlinks "Start" "Stop" "Reset").

How to add addition column?

I found this page http://msdn.microsoft.com/ru-ru/library/system.windows.controls.datagrid.autogeneratecolumns.aspx that describes how to modify or remove column, but I can not find how to add column.

You should be able to add a column in your designer like always. It'll just append that column to all the generated ones.

EDIT

Sorry, I assumed WinForms. Same idea though, just add the columns directly to the XAML:

    <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Src}" x:Name="Grid">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="Junk"></DataGridCheckBoxColumn>
            <DataGridHyperlinkColumn Header="Junk2"></DataGridHyperlinkColumn>
        </DataGrid.Columns>
    </DataGrid>

Here's the ViewModel:

public class ViewModel
{
    public ViewModel()
    {
        Src = new ObservableCollection<Item>() { new Item { Id = 1, Name = "A" }, new Item { Id = 2, Name = "B" } };
    }

    public ObservableCollection<Item> Src { get; set; }
}

public class Item{
    public int Id { get; set; }
    public string Name { get; set; }
}

And here's what it shows:

在此输入图像描述

You can either add it in XAML using <DataGrid.Columns> or you can do it in code.

Bear in mind that if you do it in XAML, by default it's going to put column at the beginning of the columns, ie before they're generated.

Alternatively, you can add it in code and specifically use the event AutoGeneratedColumns and and the code there and it will show up as the last column.

Do you have a dataset you're using as the datasource?

if so, the easier way to is add the column in the Visual Studio GUI, set the Name and DataPropertyName to something you can recognize, and then add that column to the DataSet,

//Assumes you added a column that you named 'clNew'
//Assumes you have one table in your dataset that the DGV is bound to
clNew.Name = "clNew";
clNew.DataPropertyName = "clNew";

ds.Tables[0].Columns.Add("clNew");

Column is now in the dataset to, so if you iterate through datarows you can also access it there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM