Reputation: 37
I am trying to display a database content using ListView from an .mdf database file. Here is the block of code I am using:
connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=database.mdf;Integrated Security=True");
SqlDataAdapter dataAdapter;
DataTable table;
SqlCommand command;
command = new SqlCommand("SELECT * FROM movies", connection);
dataAdapter = new SqlDataAdapter(command);
table = new DataTable();
dataAdapter.Fill(table);
moviesListView.ItemsSource = table.DefaultView;
And this is not working. I have also tried DataContext instead of ItemsSource, but it does not help. When I am using DataGrid, on the other hand, it work fine.
Could you please explain the reason for that?
Regards, Vitalii.
Upvotes: 0
Views: 987
Reputation: 1696
I just tried this one, and it worked for me:
XAML:
<ListView x:Name="osmanGrid" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="100" Margin="243,289,0,0" VerticalAlignment="Top" Width="191">
<ListView.View>
<GridView>
<GridViewColumn Header="Time" Width="50" DisplayMemberBinding="{Binding Path=Tid}"/>
<GridViewColumn Header="Acceleration" Width="70" DisplayMemberBinding="{Binding Path=Acceleration}"/>
</GridView>
</ListView.View>
</ListView>
Background class:
try
{
using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Osman\Documents\osmanDB.mdf;Integrated Security=True;Connect Timeout=30"))
{
con.Open();
SqlDataAdapter adapvare = new SqlDataAdapter("SELECT * FROM osmanTable", con);
System.Data.DataSet dsFald = new System.Data.DataSet();
adapvare.Fill(dsFald, "osmanTable");
osmanGrid.DataContext = dsFald.Tables["osmanTable"].DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
Result:
Upvotes: 2