WPF DataGrid

  1. Overview
    1. WPF DataGrid control is useful for displaying and editing tabular data
    2. Often used with DataTables

  2. Implementation
    1. Defining the DataGrid in XAML
      <DataGrid x:Name="dataGrid" />
      
    2. Bind List of Students to DataGrid.ItemsSource property
      List<Student> students = new List<Student>();
      students.Add(new Student { Id = 123, Name = "Bob", Enrolled = true });
      students.Add(new Student { Id = 456, Name = "Sue", Enrolled = false });
      students.Add(new Student { Id = 999, Name = "Angie", Enrolled = true });
      dataGrid.ItemsSource = students;
      

      Student data in DataGrid
    3. Bind DataTable
      DataTable table = new DataTable("song");
      table.Columns.Add(new DataColumn("id", typeof(int)));
      table.Columns.Add(new DataColumn("title", typeof(string)));
      table.Columns.Add(new DataColumn("artist", typeof(string)));
      table.Columns.Add(new DataColumn("albumImage", typeof(string)));
      
      DataRow row = table.NewRow();
      row["id"] = 1;
      row["title"] = "Good Vibrations";
      row["artist"] = "The Beach Boys";
      row["albumImage"] = "http://www.harding.edu/fmccown/images/broncos.gif";
      table.Rows.Add(row);
      
      row = table.NewRow();
      row["id"] = 2;
      row["title"] = "Love Me Tender";
      row["artist"] = "Elvis Presley";
      row["albumImage"] = "http://www.harding.edu/fmccown/images/cowboys.png";
      table.Rows.Add(row);
      
      // Bind the data source
      dataGrid.ItemsSource = table.DefaultView;
      
    4. Manually create columns by setting AutoGenerateColumns to false
      <DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
          <DataGrid.Columns>
              <DataGridTextColumn Binding="{Binding id}" Visibility="Hidden"/>
              <DataGridTextColumn Binding="{Binding artist}" Header="Artist"/>
              <DataGridTextColumn Binding="{Binding title}" Header="Title"/>
          </DataGrid.Columns>
      </DataGrid>
      

      DataGrid with manually defined columns

    5. Details pane
      <DataGrid.RowDetailsTemplate>
          <DataTemplate>
              <Border Background="AliceBlue">
                  <StackPanel Orientation="Vertical">
                      <TextBlock Text="{Binding title}" />
                      <Image Source="{Binding albumImage}" />
                  </StackPanel>
              </Border>
          </DataTemplate>
      </DataGrid.RowDetailsTemplate>
      

      DataGrid with detail pane

    6. Preventing the user from being able to add rows in the DataGrid
      <DataGrid CanUserAddRows="False" ... />
      
    7. Make DataGrid read-only
      <DataGrid IsReadOnly="True" ... />
      
    8. Restrict selections to single row
      <DataGrid SelectionMode="Single" ... />
      
    9. Determine which row is selected using DataGrid.SelectedItem
      DataRowView rowView = musicDataGrid.SelectedItem as DataRowView;
      if (rowView != null)
      {
          // Extract the song ID from the selected song
          int songId = Convert.ToInt32(rowView.Row.ItemArray[0]);
          Console.WriteLine("Selected song " + songId);
      }
      
    10. Implementing drag-and-drop
      private void dataGrid_MouseMove(object sender, MouseEventArgs e)
      {
          if (e.LeftButton == MouseButtonState.Pressed &&
              dataGrid.SelectedItems.Count > 0)
          {
              // Get the song ID from the currently selected row
              DataRowView rowView = dataGrid.SelectedItem as DataRowView;
              string songId = rowView.Row.ItemArray[0].ToString();
              Console.WriteLine("Dragging song " + songId);   
      
              // DragDrop.DoDragDrop             
          }
      }