The following example demonstrates a no-code approach to databinding a GridView control and database records. The BirthDate field is bound to a BasicDatePicker in the EditItemTemplate.
The SqlDataSource1 object returns a list of sample records from the [Person] database
table. The Edit button(LinkButton) allows each row to be moved
into edit mode, the BirthDate can be changed and the row updated.
The BasicDatePicker is bound(Bind) to the SelectedValue
property instead of the SelectedDate
property because the Database may return a null or DBNull value. If the SelectedValue
value is null or DBNull, the SelectedDate
is set to NullDate.
A simple [Person] Database Table was created and the [BirthDate] column was set to "Allow Nulls". See:
<form id="form1" runat="server">
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
CssClass="datatable"
Width="450px"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" />
<asp:TemplateField HeaderText="BirthDate">
<EditItemTemplate>
<bdp:basicdatepicker ID="BirthDate" DateFormat="d" runat="server" SelectedValue='<%# Bind("BirthDate") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:label ID="Label1" runat="server" Text='<%# Eval("BirthDate","{0:d}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:TestingConnectionString %>"
SelectCommand="SELECT * FROM [People]"
UpdateCommand="UPDATE [People] SET [BirthDate] = @BirthDate WHERE [ID] = @ID"
>
<UpdateParameters>
<asp:Parameter Name="ID" Type="Int32" />
<asp:Parameter Name="BirthDate" Type="DateTime" />
</UpdateParameters>
</asp:SqlDataSource>
</form>
BasicDatePicker Class | SelectedDate