asp.net gridview bind dateformat not working with update

杀马特。学长 韩版系。学妹 提交于 2019-12-11 19:05:20

问题


I have a GridView with a TemplateField column which shows a DateTime from a DataSource.

<Columns>
    <asp:CommandField ShowEditButton="True" />

    <asp:TemplateField HeaderText="Start Date">
        <EditItemTemplate>
            <asp:TextBox ID="txtDateStart" runat="server" 
                Text='<%# Bind("dtDateStart", "{0:dd/MM/yyyy}") %>'</asp:TextBox>

        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" 
                Text='<%# Bind("dtDateStart", "{0:dd/MM/yyyy}") %>'></asp:Label>
         </ItemTemplate>

    </asp:TemplateField>
</Columns>

Displaying the date in the correct format works as it should. Note that the format starts with DAY followed by MONTH.

When I switch to edit mode, change the date in the TextBox to '31-01-2013' and press the GridView's update-link i get an error: Cannot convert value of parameter 'dtDateStart' from 'System.String' to 'System.DateTime' The error is generated by the GridView not my own code. It happens before the UpdateMethod of my DataSource is called.

When i type '01-31-2012' the data is processed correctly and the value is updated into the database.

Somehow when the date is displayed it uses format dd-MM-yyyy (just as I need it to) But when it reads the new value form the TextBox it uses MM-dd-yyyy

Can somebody please help me?


回答1:


thanks for your reply. I do not know about culture settings within the website. I was assuming that proving the Bind-function with a dateformat would be sufficient.

By now I have implemented the following workaround, which is hopefully useful for others:

I have added an additional property to my class which is of type string. This property I only use for binding to the gridview.

// Original Date property //
public DateTime dtDateStart { get; set; }

// Additional Date property of type string // 
public string sDateStart
{
    get
    {
        return dtDateStart.ToString("dd/MM/yyyy");
    }
    set
    {
        dtDateStart = DateTime.ParseExact(value, "dd/MM/yyyy", null);
    }
}

I am not sure if this should be marked as the answer. But maybe others can use this as a quick workaround as well.




回答2:


I think you can use like this

         <EditItemTemplate>
            <asp:TextBox ID="txtDateStart" runat="server" 
                Text='<%# Convert.ToDateTime(Bind("dtDateStart")).ToString("dd/MM/yyyy") %>'</asp:TextBox>

        </EditItemTemplate>

this weill help you.



来源:https://stackoverflow.com/questions/14625087/asp-net-gridview-bind-dateformat-not-working-with-update

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