Data binding Datagrid control in WPF with SQL Server table

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:

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=localhostSQLEXPRESS;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");
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.

Share this post: on Google+

c#, mvc , jquery责编内容来自:c#, mvc , jquery (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Data binding Datagrid control in WPF with SQL Server table

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录