2012-12-13 33 views
2

我有一個已經綁定到數據庫的數據網格。 單擊按鈕時如何在數據網格上顯示數據?單擊按鈕時顯示數據網格

這裏是我已經試過......

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     SqlDataAdapter da = null; 
     DataSet ds = null; 
     try 
     { 
      da = new SqlDataAdapter("select * from Major", @"Data Source=Student;Initial Catalog=StudDB;Integrated Security=true;Persist Security Info=True;"); 
      da.SelectCommand.CommandTimeout = 100000; 
      ds = new DataSet(); 
      da.Fill(ds); 
      dataGrid1.ItemsSource = ds.Tables[0].DefaultView; 
     } 
     catch (SqlException ex) 
     { 
      throw ex; 
     } 
    } 
+0

請張貼一些代碼,你到目前爲止已經試過... –

+0

顯示一些代碼,請 –

+1

請查一下我的問題的變化 – user1221765

回答

1

您可以創建一個布爾值屬性,它的按鈕點擊後值的變化。 現在將此屬性綁定到DataGrid的Visibility-property。使用BooleanToVisibilityConverter轉換該值。

不要忘記在布爾屬性更改時通知視圖(NotifyPropertyChanged-Event)。

2

以下是解決方案。感謝其他回答過的人!

SqlConnection con; 
    public MainWindow() 
    { 

     InitializeComponent(); 
     try 
     { 
      con = new SqlConnection("Data Source=ComputerName;Initial Catalog=YourDBName;Persist Security Info=True;"); 
      con.Open(); 
     } 
     catch (Exception ex) 
     { 

      throw ex; 
     } 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     SqlDataAdapter da = null; 
     DataSet ds = null; 
     try 
     { 
      da = new SqlDataAdapter("select * from YourTableName",con); 
      da.SelectCommand.CommandTimeout = 100000; 
      ds = new DataSet(); 
      da.Fill(ds); 
      dataGrid1.ItemsSource = ds.Tables[0].DefaultView; 
     } 
     catch (SqlException ex) 
     { 
      throw ex; 
     } 

,並在XAML中設置的ItemSource和的AutoGenerateColumns

<DataGrid ItemsSource="{Binding YourTableName}" AutoGenerateColumns="True" Grid.Column="1" Height="423" HorizontalAlignment="Left" Margin="22,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="591" />