Inserting With a DetailsView Using a DDL
Posted by David Wier on 03/12/10 | Code Samples
This code sample shows how to insert, with ASP.net 2.0, using a DetailsView. You will probably notice the similarities to another sample (Updating Using a DDL in a GridView), like using a DropDownList for the State List, in a TemplateField ('Region' field in the database). Except this time, it's the ItemTemplate instead of the EditItemTemplate, like with the GridView Sample.
Notice 3 other things:
1. 'AutoGenerateInsertButton' is set to 'True', so it will automatically have an Insert button.
2. 'DefaultMode' is set to 'Insert', so that it will automatically go to Insert mode and not be populated.
3. The 'HeaderRow' section (below the Fields section). Here is where we add the 'Insert New Employee' Header.
To add a message (with a label, whatever), after the insert is complete, or bind another control with the new data, just add the OnRowInserted property with the DetailsView, and point it to a new Subroutine, using 'DetailsViewInsertedEventArgs' - something like this:
<html>
<head>
<meta name="GENERATOR" content="ASP Express 5.0">
<title>Inserting With a DetailsView</title>
</head>
<body>
<form id="form1" runat="server">
<asp:detailsview runat="server" id="MyDetailsView" gridlines="None" cellpadding="0"
cellspacing="1" headerstyle-backcolor="#7988B7" headerstyle-forecolor="#FFFFFF"
headerstyle-font-names="Arial" headerstyle-font-size="12" backcolor="#E0E0F6"
font-names="Arial" font-size="10" autogenerateinsertbutton="True" defaultmode="Insert"
bordercolor="Black" datasourceid="sqlDS1" datakeynames="EmployeeID" autogeneraterows="False">
<Fields>
<asp:BoundField DataField="LastName"
SortExpression="LastName" HeaderText="LastName"/>
<asp:BoundField DataField="FirstName"
SortExpression="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="Title"
SortExpression="Title" HeaderText="Title"/>
<asp:BoundField DataField="Address"
SortExpression="Address" HeaderText="Address"/>
<asp:BoundField DataField="City"
SortExpression="City" HeaderText="City"/>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:DropDownList id="ddlStates" runat="server"
DataSourceID="sqlDS2" BackColor="Pink"
selectedValue='<%# Bind("Region") %>'
DataTextField="StAbbr" DataValueField="StAbbr">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PostalCode"
SortExpression="PostalCode" HeaderText="PostalCode"/>
</Fields>
<HeaderTemplate>
Insert New Employee
</HeaderTemplate>
</asp:detailsview>
<asp:sqldatasource id="sqlDS1”" runat="Server"
insertcommand="Insert into Employees ([FieldList]) values ('@' before each field in List)"
connectionstring="<%$ ConnectionStrings:YourConnStringGoesHere %>">
</asp:sqldatasource>
<asp:sqldatasource id="sqlDS2" runat="Server"
selectcommand="SELECT STabbr From states"
datasourcemode="DataSet"
connectionstring="<%$ ConnectionStrings:YourConnStringGoesHere %>">
</asp:sqldatasource>
</form>
</body>
</html>