ListView不显示数据库中的数据

时间:2017-07-16 08:10:19

标签: c# wpf listview

我试图通过listview在WPF中显示数据库中的一列数据。这是我的代码:

private void OpenExistingBtn_Click(object sender, RoutedEventArgs e)
{
    OpenOrNew.Visibility = System.Windows.Visibility.Collapsed;
    OpenExisting.Visibility = System.Windows.Visibility.Visible;
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select docName from [table]";
    cmd.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    dataTable.DataContext = dt.DefaultView;
    con.Close();
}

我的XAML:

<Grid x:Name="OpenExisting" Visibility="Collapsed">
    <Grid Background="Black" Opacity="0.5">
        <Border MinWidth="250" Background="{x:Null}" BorderThickness="0" CornerRadius="4" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ListView x:Name="dataTable">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Select a file" DisplayMemberBinding="{Binding Path=docName}"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </Border>
    </Grid>
</Grid>

我的数据库中肯定有数据,运行代码时没有错误。 这就是我的数据库的样子:

This is what my database looks like

1 个答案:

答案 0 :(得分:1)

您必须将ListView.ItemsSource属性设置为dataTable.DefaultView。例如:

OpenExisting.ItemsSource = dt.DefaultView