Foxman
Foxman

Reputation: 189

Exception when adding datatemplate to a dynamically created DataGrid

table code:

C#:

           Tracker.MyFile[] fileData = tracker.GetFileData();

            DataTable fileDataTable = new DataTable();
            fileDataTable.Columns.Add("Name", typeof(string));
            fileDataTable.Columns.Add("Category", typeof(string));
            fileDataTable.Columns.Add("Length", typeof(string));

            foreach (Tracker.MyFile file in fileData)
            {
                DataRow dr = fileDataTable.NewRow();
                dr["Name"] = file.DownloadName;
                dr["Category"] = file.Category;
                dr["Length"] = FormatLength(file.Length);

                fileDataTable.Rows.Add(dr);
            }               

XAML:

                   <DataGrid Name="dgFiles" AutoGenerateColumns="True"                   IsReadOnly="True" ItemsSource="{Binding}">
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Name ="Download" Content="Download"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>                  
                </DataGrid>

exception:

Items collection must be empty before using ItemsSource.

Now, does the exception mean that you cannot add custom columns to an already created table? If yes, is there any other way to add the custom column?

Another thing I tried was adding a button column to the table through the code with the C# Button class but it didn't render the button at runtime, only showed a string that showed the button type.

thanks.

Upvotes: 0

Views: 52

Answers (1)

blindmeis
blindmeis

Reputation: 22435

if you want add some columns you have to do this under DataGrid.Columns otherwise you add this to the ItemsCollection.

               <DataGrid Name="dgFiles" AutoGenerateColumns="True"                   IsReadOnly="True" ItemsSource="{Binding}"> 
      <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name ="Download" Content="Download"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>  
        </DataGrid.Columns>                
            </DataGrid>

Upvotes: 3

Related Questions