DataGrid repeats the data retrieved from database in a single row twice

偶尔善良 提交于 2020-01-07 03:25:34

问题


I am working on a point of sale project in WPF and i want to retrieve all the records (associated with the current or last customer id) in to datagrid. I have done the same work in other project while selecting the * from a table and retrieving it. But this time don't know why this code doesn't work.i am including the output image with my question kindly have a look at that too.

<DataGrid x:Name="dataGrid" ItemsSource="{Binding DataSource}" HorizontalAlignment="Left" Margin="115,312,0,0" VerticalAlignment="Top" Height="376" Width="864">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="Background" Value="#1C75BC" />
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="BorderBrush" Value="Black" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="Height" Value="20" />
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Header="BarCode" Binding="{Binding BarCode}" Width="*" />
        <DataGridTextColumn Header="ProductName" Binding="{Binding ProductName}"  Width="*"/>
        <DataGridTextColumn Header="UnitPrice" Binding="{Binding UnitPrice}" Width="*" />
        <DataGridTextColumn Header="SalePrice" Binding="{Binding SalePrice}" Width="*" />
        <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" Width="*" />                       
    </DataGrid.Columns>
</DataGrid>
private void FillDataGrid(int counttt)
{
    SqlConnection connn = db.getConnection();
    connn.Open();
    string CmdString = string.Empty;
    //DateTime dateTime = DateTime.UtcNow.Date;
    //String d = (dateTime.ToString("dd/MM/yyyy"));
    CmdString = "SELECT BarCode, ProductName, UnitPrice, SalePrice, Quantity From CustomerSale WHERE CId = '" + counttt + "'";
    SqlCommand cmd = new SqlCommand(CmdString, connn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("CustomerSale");
    sda.Fill(dt);
    dataGrid.ItemsSource = dt.DefaultView;
    connn.Close();
}


回答1:


Disable DataGrid.AutoGenerateColumns. You created columns for each data property in markup (<DataGrid.Columns>) and when ItemsSource is set, DataGrid also generates columns for every property because default value for AutoGenerateColumns is true.

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding DataSource}" ...


来源:https://stackoverflow.com/questions/42993716/datagrid-repeats-the-data-retrieved-from-database-in-a-single-row-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!