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" />
		<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">
				<asp:dropdownlist runat="server" id="ddStudent"></asp:dropdownlist>

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";
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: