Duplicate data on datagrid

Asked

Viewed 156 times

1

I am developing an application in WPF and when I fill the datagrid via code it returns the duplicate value. I am using Entity Framework.

inserir a descrição da imagem aqui

XAML

<DataGrid x:Name="dataLocal" Margin="10,111,11,10" IsReadOnly="True" SelectionMode="Single">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ID}" Header="ID" Visibility="Hidden"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding CidadeInicial}" Header="Cidade Inicial"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding CidadeDestino}" Header="Cidade Destino"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Carga}" Header="Carga"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Kmrodado}" Header="KM Rodado"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Status}" Header="Status"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

Code C#

private void preencheDGV()
    {
        //this.DataContext = local.dadosLocais.Local;
        dataLocal.ItemsSource = local.dadosLocais.Select(x => new
        {
            x.ID,
            x.CidadeInicial,
            x.CidadeDestino,
            x.Carga,
            x.Kmrodado,
            x.Status
        }).ToList();
    }

Apart from this doubt, I have the following question: How to apply an Autosize in the Columns of this datagrid?

1 answer

1


Set the property AutoGenerateColumns for false:

<DataGrid x:Name="dataLocal" Margin="10,111,11,10" IsReadOnly="True" SelectionMode="Single" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ID}" Header="ID" Visibility="Hidden"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding CidadeInicial}" Header="Cidade Inicial"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding CidadeDestino}" Header="Cidade Destino"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Carga}" Header="Carga"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Kmrodado}" Header="KM Rodado"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Status}" Header="Status"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

On the other issue, the correct thing to do is ask another question, but just set the property ColumnWidth as *:

<DataGridTextColumn Binding="{Binding Status}" Header="Status" ColumnWidth="*">
</DataGridTextColumn>
  • 1

    Thanks, super complete reply. It helped a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.