Reload

DateTime Suite Samples

Auto databinding to SQLDataSource using GridView Control

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.

Remarks

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:

Person Database Table

Example

NameBirthDate 
Kelly 5/12/2008 Edit
Neil 11/18/2008 Edit
Nelson 4/1/2008 Edit
Max 5/29/2008 Edit
Darren 9/25/2008 Edit
Chris 4/30/2008 Edit

Code

<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>

See Also

BasicDatePicker Class | SelectedDate