C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: Visual Studio will create the DataGrid_Loaded event handler. This is where we assign the ItemsSource property.
Loaded: In the DataGrid_Loaded method, we create a List of Dog objects. These objects are automatically traversed by the DataGrid.
ItemSource: The ItemsSource property accepts only an IEnumerable. Many types (like array and List) implement the IEnumerable interface.
Tip: If the IEnumerable (that is used with ItemSource) uses objects, each object's properties are evaluated.
IEnumerableCaution: ItemsSource does not support a List of arrays. It is better, and more efficient, to simply use objects (such as the Dog class).
Example markup: XAML
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Loaded="DataGrid_Loaded"/>
</Grid>
</Window>
Example code: C#
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
class Dog
{
public string Name { get; set; }
public int Size { get; set; }
public Dog(string name, int size)
{
this.Name = name;
this.Size = size;
}
}
namespace WpfApplication14
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
// ... Create a List of objects.
var items = new List<Dog>();
items.Add(new Dog("Fido", 10));
items.Add(new Dog("Spark", 20));
items.Add(new Dog("Fluffy", 4));
// ... Assign ItemsSource of DataGrid.
var grid = sender as DataGrid;
grid.ItemsSource = items;
}
}
}
Tip: I recommend this option for most programs that use DataGrids of nontrivial size. The color shown (Coral) is not ideal.
Example markup 2: XAML
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
AlternatingRowBackground="Coral"
Loaded="DataGrid_Loaded"/>
</Grid>
</Window>
Then: We hook up the SelectionChanged event by adding the DataGrid_SelectionChanged method.
Note: I apologize for the complex example. The important part to examine is the DataGrid_SelectedChanged method.
Example markup 3: XAML
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
SelectionChanged="DataGrid_SelectionChanged"
Loaded="DataGrid_Loaded"/>
</Grid>
</Window>
Example code 3: C#
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
class Dog
{
public string Name { get; set; }
public int Size { get; set; }
public Dog(string name, int size)
{
this.Name = name;
this.Size = size;
}
}
namespace WpfApplication14
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
// ... Create.
var items = new List<Dog>();
items.Add(new Dog("Fido", 10));
items.Add(new Dog("Spark", 20));
items.Add(new Dog("Fluffy", 4));
items.Add(new Dog("Rover", 100));
items.Add(new Dog("Mister Mars", 30));
// ... Assign.
var grid = sender as DataGrid;
grid.ItemsSource = items;
}
private void DataGrid_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
// ... Get SelectedItems from DataGrid.
var grid = sender as DataGrid;
var selected = grid.SelectedItems;
// ... Add all Names to a List.
List<string> names = new List<string>();
foreach (var item in selected)
{
var dog = item as Dog;
names.Add(dog.Name);
}
// ... Set Title to selected names.
this.Title = string.Join(", ", names);
}
}
}
Here: We use the program as in previous examples, but we omit some repeated parts of the source file.
Tip: We can get a TextBox object (and its Text property) from the EditingElement property of the DataGridCellEditEndingEventArgs.
Example markup 4: XAML
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
CellEditEnding="DataGrid_CellEditEnding"
Loaded="DataGrid_Loaded"/>
</Grid>
</Window>
Example method: C#
private void DataGrid_CellEditEnding(object sender,
DataGridCellEditEndingEventArgs e)
{
// ... Get the TextBox that was edited.
var element = e.EditingElement as TextBox;
var text = element.Text;
// ... See if the text edit should be canceled.
// We cancel if the user typed a question mark.
if (text == "?")
{
// ... Cancel the edit.
this.Title = "Invalid";
e.Cancel = true;
}
else
{
// ... Show the cell value in the title.
this.Title = "You typed: " + text;
}
}
Here: We add 100 objects to a List, and use that with ItemsSource. We scroll to the final element in the collection (the last row).
Note: Please see the first example on this page for more information about using the ItemsSource property.
Example code: C#
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
class Order
{
public int Size { get; set; }
}
namespace WpfApplication14
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
// ... Create Orders.
var items = new List<Order>();
for (int i = 0; i < 100; i++)
{
items.Add(new Order { Size = i });
}
// ... Use ItemsSource.
var grid = sender as DataGrid;
grid.ItemsSource = items;
// ... Scroll into view.
grid.ScrollIntoView(items[items.Count - 1]);
}
}
}
Then: As the user edits the DataGrid, the List objects are changed. The List is stored in a field on the MainWindow class.
File: data.txt
Harry,Ford,ABC,1
Sally,Martin,POE,2
Edith,Milner,QED,0
James,Lawry,XYZ,8
Example: XAML
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Closing="Window_Closing">
<Grid>
<DataGrid
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Loaded="DataGrid_Loaded"/>
</Grid>
</Window>
Example: C#
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
class Patient
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Code { get; set; }
public int Insurance { get; set; }
public Patient(string line)
{
string[] parts = line.Split(',');
this.FirstName = parts[0];
this.LastName = parts[1];
this.Code = parts[2];
this.Insurance = int.Parse(parts[3]);
}
public string GetLine()
{
return this.FirstName + "," + this.LastName + "," + this.Code + "," +
this.Insurance.ToString();
}
}
namespace WpfApplication14
{
public partial class MainWindow : Window
{
List<Patient> _list;
public MainWindow()
{
InitializeComponent();
}
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
// ... Get data.
var patients = new List<Patient>();
using (StreamReader reader = new StreamReader("data.txt"))
{
while (true)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
patients.Add(new Patient(line));
}
}
// ... Set field.
this._list = patients;
// ... Use ItemsSource.
var grid = sender as DataGrid;
grid.ItemsSource = patients;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
// ... Write the DataGrid at Closing.
using (StreamWriter writer = new StreamWriter("data.txt"))
{
foreach (Patient patient in this._list)
{
writer.WriteLine(patient.GetLine());
}
}
}
}
}