ASP.Net GridView Error: Conversion from string '' to type Date is not valid

Last Reply 28 days ago By Hariom

Posted one month ago

Thank you for help

I have label on form I display date on it

I try display this label in gridview but every time the column appears

Empty

here is my code :

<asp:TemplateField HeaderText="التاريخ">
    <ItemTemplate>
        <asp:Label ID="txtdats" runat="server" Text="<% #Label4.Text  %>" >  </asp:Label>
    </ItemTemplate>
</asp:TemplateField>

And i tried another codes like :

Text="<% #CDate(Label4.Text) %>" > and error appears

Conversion from string "" to type 'Date' is not valid.'

Posted one month ago

Hi y.alim,

Refer below sample.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:TemplateField HeaderText="Date">
            <ItemTemplate>
                <asp:Label ID="txtdats" runat="server">  </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Rows.Add(1);
        dt.Rows.Add(2);
        dt.Rows.Add(3);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        (e.Row.FindControl("lblDate") as Label).Text = DateTime.Now.ToString("dd MMM yyyy");
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add("Id")
        dt.Rows.Add(1)
        dt.Rows.Add(2)
        dt.Rows.Add(3)
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        TryCast(e.Row.FindControl("lblDate"), Label).Text = DateTime.Now.ToString("dd MMM yyyy")
    End If
End Sub

Screenshot


Posted 28 days ago

 

<asp:TemplateField HeaderText="التاريخ">
    <ItemTemplate>
        <asp:Label ID="txtdats" runat="server" Text='<%#String.Format("{0:dd/MMM/yyyy}",Eval("CDate"))%>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>