Reputation: 761
I'm trying to display a column of data from a database in WPF through a listview. Here's my code:
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();
}
My 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>
There is definitely data in my database, and there are no errors when running the code. This is what my database looks like:
Upvotes: 0
Views: 68
Reputation: 5083
You have to set your ListView.ItemsSource
property to dataTable.DefaultView
. Example:
OpenExisting.ItemsSource = dt.DefaultView
Upvotes: 1