ListView和数据库

时间:2014-12-06 18:00:26

标签: c# wpf listview

我正在尝试使用.mdf数据库文件中的ListView显示数据库内容。这是我正在使用的代码块:

        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;

这不起作用。我也尝试过DataContext而不是ItemsSource,但它没有帮助。另一方面,当我使用DataGrid时,它工作正常。

你能解释一下原因吗?

此致 维塔利。

1 个答案:

答案 0 :(得分:2)

我刚试过这个,它对我有用:

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>

背景课程:

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);
        }

结果:

enter image description here