DetailsView ObjectDataSource OnUpdate无法从String转换为DateTime

时间:2017-02-13 13:30:44

标签: c# datetime webforms objectdatasource detailsview

编辑模式下的

DetailsView无法将只读DateTime字段转换为String
我解决了这个问题,但在我看来,解决问题的方法并不是最优雅的。

为什么会这样?

详情查看编辑模式
DetailsView

点击'更新' 后出现例外情况 Exception

ASPX

<asp:DetailsView
    ID="PersonDetails" runat="server"
    DataSourceID="PersonSource"
    ItemType="SubjectD.Models.HbPerson"
    AllowPaging="false"
    AutoGenerateRows="false"
    AutoGenerateDeleteButton="true"
    AutoGenerateEditButton="true"
    AutoGenerateInsertButton="true">
    <Fields>
        <asp:BoundField HeaderText="Id" DataField="Id" SortExpression="Id" ReadOnly="true" />
        <asp:BoundField HeaderText="NameFirst" DataField="NameFirst" SortExpression="NameFirst" />
        <asp:BoundField HeaderText="NameMiddle" DataField="NameMiddle" SortExpression="NameMiddle" />
        <asp:BoundField HeaderText="NameLast" DataField="NameLast" SortExpression="NameLast" />
        <asp:BoundField HeaderText="SocialNumber" DataField="SocialNumber" SortExpression="SocialNumber" />
        <asp:BoundField HeaderText="Created" DataField="Created" SortExpression="Created" 
            ReadOnly="true" /> <!-- DateTime -->
        <asp:BoundField HeaderText="Modified" DataField="Modified" SortExpression="Modified" 
            ReadOnly="true" /> <!-- DateTime -->
    </Fields>
</asp:DetailsView>
<asp:ObjectDataSource
    ID="PersonSource" runat="server"
    TypeName="SubjectD.Business.BizPerson"
    DataObjectTypeName="SubjectD.Models.HbPerson"
    EnablePaging="true"
    MaximumRowsParameterName="maxRows"
    StartRowIndexParameterName="startRowIndex"
    SortParameterName="sortExpression"
    SelectCountMethod="Count"
    SelectMethod="SelectPerson"
    UpdateMethod="Update">
    <SelectParameters>
        <asp:Parameter Name="Id" DefaultValue="0" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>


我做了什么来解决它
我在OnItemUpdating

处理了DetailsView事件
<asp:DetailsView
    ...
    OnItemUpdating="PersonDetails_ItemUpdating">
</asp:DetailsView>

这样做了:

protected void PersonDetails_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
    var modified = e.OldValues[5];
    e.NewValues.Add("Modified", modified);
}

现在不会发生例外 这是解决这个问题的正确方法吗?

0 个答案:

没有答案