DataGrid Binding



The DataGrid control is probably the easiest object made to connect to data. It is designed like a spreadsheet made of columns, rows, and cells. This makes it possible to display all values of relatively small table or to display as many records as its dimensions can allow. To make this possible, the DataGrid control is equipped with the DataSource property that allows you to specify the data set object that holds the records the control will display. The data set object can be of type DataTable, DataView, DataSet, DataViewManager, a class derived from the IListSource or the IList interfaces.

Besides the DataGrid.DataSource property, the control is also equipped with a DataMember property that allows you to specify the name of the object, such as a table.

Imagine you have a SQL Server database named Video Collection and that is equipped with a table named Videos created with the following columns:

Imagine you had created a few records as follows:

You can bind this table to a DataGrid as follows:

private void btnLoad_Click(object sender, System.EventArgs e)
	SqlConnection cnnVideos = new SqlConnection(
		"Data Source=(local);Database='VideoCollection';Integrated Security=yes");

	string strVideos = "SELECT VideoID, VideoTitle, Director, YearReleased, " +
			"VideoLength, Rating FROM Videos;";
	SqlCommand    cmdVideos = new SqlCommand(strVideos, cnnVideos);

	SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);

	DataSet setVideos = new DataSet("VideoCollection");
	this.dataGrid1.DataSource = setVideos;
	this.dataGrid1.DataMember = setVideos.Tables[0].TableName;


private void btnClose_Click(object sender, System.EventArgs e)

Home Copyright © 2005-2012 FunctionX