Reputation: 4791
I'm trying to add 3 columns of checkboxes in my data grid.
First, with method I put some string values in two columns and after that I want to add 3 more columns of checkboxes.
I found this solution in other post like this one:
DataGridCheckBoxColumn chbcolumn = new DataGridCheckBoxColumn();
for (int j = 0; j == 3; j++)
{
tabela.Columns.Add(chbcolumn);
}
(tabela is the name of the data grid defined in XAML like this):
<DataGrid AutoGenerateColumns="True" Height="206" HorizontalAlignment="Left" Margin="12,265,0,0" Name="tabela" VerticalAlignment="Top" Width="556" SelectionChanged="tabela_SelectionChanged" Grid.RowSpan="2" />
Now this works good for adding one column, but I need two more. I've tried putting that code in for loop, but then I don't get nothing, so obliviously that was a stupid idea. I've tried some other properties of Columns too, but didn't manege to find one that works in this case.
Also, do you maybe know a way to access the name of Columns and changing them? Cause I need 3 different names for those columns.
Does anyone maybe knows some easy way to solve this?
Update:
I make it this way, maybe not the perfect solution, but it did a job.
DataGridCheckBoxColumn chbcolumn1 = new DataGridCheckBoxColumn();
DataGridCheckBoxColumn chbcolumn2 = new DataGridCheckBoxColumn();
DataGridCheckBoxColumn chbcolumn3 = new DataGridCheckBoxColumn();
chbcolumn1.Header = "Controller";
chbcolumn2.Header = "Area";
chbcolumn3.Header = "Service";
tabela.Columns.Add(chbcolumn1);
tabela.Columns.Add(chbcolumn2);
tabela.Columns.Add(chbcolumn3);
Upvotes: 0
Views: 2065
Reputation: 1577
Instead of using code behind, try it with XAML. A simple checkbox column can be defined like this
<DataGrid ItemsSource="{Binding MyDataList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="TextColumn1" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="TextColumn1" Binding="{Binding LastName}" />
<DataGridTextColumn Header="TextColumn1" Binding="{Binding Address}" />
<DataGridTemplateColumn Header="CheckBoxColumn1">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="CheckBoxColumn2">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsAlive}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="CheckBoxColumn3">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsParticipating}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Upvotes: 5
Reputation: 12295
You are adding the same instance Column in a loop. Try this
for (int j = 0; j == 3; j++)
{
DataGridCheckBoxColumn chbcolumn = new DataGridCheckBoxColumn();
tabela.Columns.Add(chbcolumn);
}
Upvotes: 0