GeekDork.com - work smarter not harder

Samples > Databound controls inside a Datagrid

Here is an example of a datagrid with a dropdownlist in a template column. The data comes from the standard NorthWind database. The working example is at the bottom of the page.

A single DataSet is populated with two DataTables.
strSQL = "SELECT LastName, FirstName, EmployeeID "
strSQL &= "FROM Employees ORDER BY Lastname, Firstname"
objCommand.CommandText = strSQL
objDataAdapter.Fill(objDataSet, "Employee")

strSQL = "SELECT t.TerritoryDescription, et.EmployeeID, t.TerritoryID "
strSQL &= "FROM Territories AS t, EmployeeTerritories AS et "
strSQL &= "WHERE t.TerritoryID=et.TerritoryID "
strSQL &= "ORDER BY TerritoryDescription"
objCommand.CommandText = strSQL
objDataAdapter.Fill(objDataSet, "Territory")
A DataRelation is added to the DataSet to establish the parent-child relationship between the tables.
objParentCol = objDataSet.Tables("Employee").Columns("EmployeeID")
objChildCol = objDataSet.Tables("Territory").Columns("EmployeeID")
objRelation = New DataRelation("EmployeeTerritories", objParentCol, objChildCol)
objDataSet.Relations.Add(objRelation)
The markup for the control uses data binding syntax to specify the datasource for the inner dropdown list. The important part is where the child rows are obtained. In the following code, "Container.DataItem" is the dataitem of the grid, i.e. a DataRow. From that you can call the CreateChildView method and pass it a DataRelation name. This will return a DataView of only the related records based on the DataRelation created in the code when the DataSet is created.
<asp:templatecolumn headertext="Child Dropdownlist">
	<itemtemplate>
		<asp:dropdownlist runat="server"
			datasource='<%# Container.DataItem.CreateChildView("EmployeeTerritories") %>'
			datatextfield="TerritoryDescription" datavaluefield="TerritoryID" />
	</itemtemplate>
</asp:templatecolumn>
Here is the working example:

NameChild Dropdownlist
Buchanan, Steven
Callahan, Laura
Davolio, Nancy
Dodsworth, Anne
Fuller, Andrew
King, Robert
Leverling, Janet
Peacock, Margaret
Suyama, Michael
GeekDork.com - Contact Us
This site is optimized for Internet Explorer.