How to bind a table in a dataset to a WPF datagrid in C# and XAML

前端 未结 1 705
Happy的楠姐
Happy的楠姐 2020-12-01 13:35

I have been searching to hours for something very simple: bind a WPF datagrid to a datatable in order to see the columns at design-time. I can’t get any of the examples to w

相关标签:
1条回答
  • 2020-12-01 13:49

    Using the Microsoft DataGrid in the following way works for me:

    In XAML I include the DataGrid:

        <WpfToolkit:DataGrid
            Grid.Row="4" Grid.Column="0"
            ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
        </WpfToolkit:DataGrid>
    

    In my view model I expose a DataView:

      public DataView GridData
      {
         get
         {
            DataSet ds = new DataSet("MyDataSet");
    
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
               SqlCommand cmd = conn.CreateCommand();
               cmd.CommandType = CommandType.Text;
               cmd.CommandText = "SELECT * FROM HumanResources.Employee";
    
               SqlDataAdapter da = new SqlDataAdapter(cmd);
               da.Fill(ds);
            }
    
            return ds.Tables[0].DefaultView;
         }
      }
    
    0 讨论(0)
提交回复
热议问题