DataGrid control in WPF control can be used to display collection of items.There are some other controls which are used for dispalying a collection of items.
Some other controls which are used for displaying collection of items are:
- ComboBox
- ListBox
- TabControl
These controls derive from the base class ItemsControl.ItemsControl defines some common properties and methods used by the other collection controls.The different controls differs how they display the data.
DataGrid control class also derives from ItemsControl class.It displays data in the form of grid ,consisting of multiple rows and columns.
Here we will bind datagrind control with a data table which we will populate in the code behind.
TO bind the datagrid with data we need to set its ItemsSource property to a collection which implements IEnumerable interface.The collection of objects in the collection are used to define rows in the datagrid.
If we want the datagrid to be notified of addition or removal of items in the bound collection the collection should implement INotifyCollectionChanged interface.If we want the changes in the objects to be reflected in the datagrid then the objects in the collection should implement INotifyPropertyChanged interface.
In the following example we are binding the students table in the SQL server database to the datagrid.We have added the grid in xaml using the following code:
<Grid> <DataGrid x:Name="grdStudents" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="False" CanUserSortColumns="True"/> </Grid>
We have set the name of the grid as grdStudents.This is important since we will be data binding our grid to the student table using the code behind.
In the code behind we are binding the grid to the list of students.We are fetching the list of students from students table in StudentDb.
public void RetreiveData() { string ConString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=StudentDb; Integrated Security=True;"; string CmdString = string.Empty; using (SqlConnection con = new SqlConnection(ConString)) { CmdString = "SELECT name,rollno,age FROM students"; SqlCommand cmd = new SqlCommand(CmdString, con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable("students"); sda.Fill(dt); grdStudents.ItemsSource = dt.DefaultView; }
You can prevent automatic column generation by setting the AutoGenerateColumns property to false. This is useful if you want to create and configure all columns explicitly.We get the list of students in the datagrid on running the above code.
Leave a Reply