Home > Programming > Creating a Dropdown in an ASP.NET GridView Control

Creating a Dropdown in an ASP.NET GridView Control


To create a Dropdown control in an ASP.NET GridView control, you create a template field and wire the behavior to populate the dropdown in the RowDataBound event of the GridView.  Here is a simple example.

In the GridView, we created the template field with an ItemTemplate and inserted the Dropdown control.  Also, note that we wired up the OnRowDataBound event in the GridView’s tag.

<asp:gridview id="gvSeminarSchedule" onrowdatabound="gvSeminarSchedule_RowDataBound"
	runat="server" autogeneratecolumns="False" onselectedindexchanged="gvSeminarSchedule_SelectedIndexChanged"
	onselectedindexchanging="gvSeminarSchedule_SelectedIndexChanging" datakeynames="SeminarScheduleID">
	<alternatingrowstyle cssclass="GridRowAlternate" />
	<rowstyle cssclass="GridRowStandard" />
	<headerstyle cssclass="ItemLabelCenter" />
	<selectedrowstyle cssclass="GridRowSelected" />
	<columns>
		<asp:boundfield datafield="SeminarScheduleID" headertext="ID" />
		<asp:boundfield datafield="FormattedStartDate" headertext="Seminar Start" htmlencode="false" />
		<asp:boundfield datafield="FormattedEndDate" headertext="Seminar End" htmlencode="false" />
		<asp:boundfield datafield="RegisterStartDateString" headertext="Register Start" />
		<asp:boundfield datafield="RegisterEndDateString" headertext="Register End" />
		<asp:boundfield datafield="RegisterEarlyPriceEndDateString" headertext="Register Early Price End" insertvisible="False" readonly="True" />
		<asp:templatefield headertext="Students">
			<itemtemplate>
				<asp:dropdownlist runat="server" id="ddStudent"></asp:dropdownlist>
			</itemtemplate>
		</asp:templatefield>
	</columns>
</asp:gridview>

In the page behind, we are testing for a DataRow, and if it is then we find the DropDown control instance for the row and populate it.

protected void gvSeminarSchedule_RowDataBound( object sender, GridViewRowEventArgs e )
{
	if ( e.Row.RowType == DataControlRowType.DataRow )
	{
		SeminarSchedule seminarSchedule = new SeminarSchedule();
		seminarSchedule.SeminarScheduleID = e.Row.Cells[ 0 ].Text.ToInt();
		DropDownList ddl = (DropDownList)e.Row.FindControl( "ddStudent" );
		ddl.DataSource = seminarSchedule.ListStudentsByNameLastFirst();
		ddl.DataMember = "PersonID";
		ddl.DataTextField = "FullNameLastFirst";
		ddl.DataBind();
	}
}
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment