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

前端 未结 1 711
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:

        
        
    

    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)
提交回复
热议问题