单击Button时显示datagrid

时间:2012-12-13 09:57:04

标签: c# wpf xaml wpfdatagrid

我有一个已绑定到数据库的数据网格。 如何在单击按钮时在数据网格上显示数据?

这是我尝试过的......

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

2 个答案:

答案 0 :(得分:2)

这是解决方案。感谢hav回复的其他人!

    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" />

答案 1 :(得分:1)

您可以创建一个布尔属性,该值在按钮单击后更改。 现在,将此属性绑定到DataGrid的Visibility属性。使用BooleanToVisibilityConverter转换值。

当布尔属性发生变化时,别忘了通知你的View(NotifyPropertyChanged-Event)。