DataGrid在单行中重复两次从数据库中检索到的数据 [英] DataGrid repeats the data retrieved from database in a single row twice
问题描述
我正在WPF中进行销售点项目,我想将所有记录(与当前或最后一个客户ID关联)检索到datagrid中。从表中选择*并检索它时,我在其他项目中也做了相同的工作。但这一次不知道为什么这段代码不起作用。我也将输出图像包含在我的问题中,也请仔细看看。
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();
}
推荐答案
禁用 DataGrid.AutoGenerateColumns
。您为标记中的每个数据属性创建了列(< DataGrid.Columns>
),并且在设置ItemsSource时,DataGrid还会为每个属性生成列,因为AutoGenerateColumns的默认值为 true
。
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}" ...
这篇关于DataGrid在单行中重复两次从数据库中检索到的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!