开发者

How to convert string to datetime in DataObject with ObjectDataSource

I have one class for selecting, updating and deleting record in db (sql server 2008) and one class for represent table record, i think it's call 'Activ record' design pattern. Now, I have GriwView with editing, selecting and deleting items. Data source for this grid is ObjectDataSource:

<asp:ObjectDataSource ID="ObjectDataSource" runat="server" 
        TypeName="DBOrdinacniDoby.Hours" 
        DataObjectTypeName="DBOrdinacniDoby.Hour"
        onobjectcreating="ObjectDataSource_ObjectCreating" 
        SelectMethod="GetAll"
        UpdateMethod="EditHour">
    </as开发者_StackOverflow社区p:ObjectDataSource>

In grid is types like: int, nvarchar, date, time and bit. Method's EditHour parameter is class of Hour. Hour have construct without parameters, but when program sets property 'DateFrom' - DataTime type in C# and Date in SQL Server, I got Exception: System.InvalidOperationException, Can't convert form string to DateTime.

Please help, how can I fix it? Thanks, Sebastian

EDIT: I try add event handler for GridView RowUpdating and manually convert do DateTime like this:

e.NewValues[1] = Convert.ToDateTime(e.NewValues[1].ToString());

But still not working... :(


Try to add UpdateParametes where you define Type of parameter.

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
     UpdateMethod="UpdateUser" ...>
        <UpdateParameters>
            <asp:Parameter Name="CreationDate" Type="DateTime" />
            <asp:Parameter Name="LastLoginDate" Type="DateTime" />
        </UpdateParameters>

Worked for me.


One way to fix this, is to subscribe to the Updating Event of the ObjectDataSource. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.updating.aspx

Codesample from one of my apps (where Article is my Business Layer class):

protected void odsArticleDetail_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
    Article item = (Article)(e.InputParameters["item"]);
    TextBox txtDate = (TextBox)this.dvArticleDetail.FindControl("txtDate");
    if (!String.IsNullOrEmpty(txtDate.Text))
    {
        item.PublishDate = DateTime.ParseExact(txtDate.Text, "dd.MM.yyyy", System.Globalization.CultureInfo.GetCultureInfo("de-DE"));
    }
    else
    {
        item.PublishDate = DateTime.Now;
    }
}

e.InputParameters["item"] must match the parametername of your Business Layer method:
In my case:

public void UpdateArticle(Article item)
{
 // save changes into db
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜