Datecolumn: Unable to cast object of type 'System.DateTime' to type 'System.String'

非 Y 不嫁゛ 提交于 2019-12-24 08:26:02

问题


I have a sql table with a column [WelcomeSent] with type: Datetime and null values existing in this column

I have this code to get the values from my DB and store them in a grid:

var result = (from i in dc.vw_Users where i.id == id select i).ToList(); //error line
storeUsers.DataSource = result;
storeUsers.DataBind();

In my grid there is a column:

<ext:DateColumn runat="server" ID="ColUsersWelcomeSent"     DataIndex="WelcomeSent"     Text="WelcomeSent"  Width="80"  Format="dd/MM/yyyy" Hidden="true"></ext:DateColumn>

But when I run it I receive this error:

Unable to cast object of type 'System.DateTime' to type 'System.String'

Anyone know how I can fix that?


回答1:


you need to convert toString() your date value in linq result object before assign in storeUsers.DataSource = result;




回答2:


Solved it by getting each column separately and parsing Date Column:

var result = from i in dc.vw_Users
    where i.id == id
    select new
    {
        i.UserId,
        i.id,
        i.SiId,
        i.FullName,
        i.UserName,
        i.RoId,
        i.Ro,
        i.Email,
        WelcomeSent =
            i.WelcomeSent != null && i.WelcomeSent.ToString().Length > 0
                ? DateTime.Parse(i.WelcomeSent.ToString())
                : new DateTime(),
        i.Signed,
        i.IsPri,
        i.IsApproved,
        IsLocked = i.IsLockedOut,
        i.LoginStatus,
        i.LastLoginDate,
        i.SignRights,
        i.LastPasswordChangedDate,
        i.FailedPasswordAttemptCount,
        i.CompleteDate,
        i.AccessDate,
        i.CertificationDate,
        i.CertificateId,
        i.progress
    };


来源:https://stackoverflow.com/questions/42694344/datecolumn-unable-to-cast-object-of-type-system-datetime-to-type-system-stri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!