2014-12-06 60 views
0

我想從.mdf數據庫文件中使用ListView顯示數據庫內容。這裏是我使用的代碼塊: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時,它工作正常。

請問您能解釋一下原因嗎?

Regards, Vitalii。

+0

什麼你做 意思是_not working_?您收到異常或錯誤訊息? – 2014-12-06 18:02:01

+0

只是看不到內容(ListView爲空)。 – witua 2014-12-06 18:03:52

+0

愚蠢的問題:但是,你是否檢查'table'是否實際上包含任何行? – 2014-12-06 18:06:06

回答

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

+0

正如我所說的,DataGrid工作正常。我想知道關於ListView。 – witua 2014-12-06 18:18:42

+0

只需更改您的sql表名和連接字符串。此外,您必須綁定到的表列的名稱(DisplayMemberBinding) – 2014-12-06 18:35:50