'Get Gridview Textbox value as Date Format

I am using asp.net Textbox inside Gridview and accessing Textbox using below code;

ASP.NET

<ItemTemplate>                       
     <asp:TextBox runat="server" TextMode="Date"  Title="Select Received Date." AutoCompleteType="Disabled" placeholder="Receive On (Date)" aria-describedby="basic-addon1" ID="txtRcvOn" Visible="false" ></asp:TextBox>
</ItemTemplate>

C#

TextBox txtRcvOn0 = (row.Cells[7].FindControl("txtRcvOn") as TextBox); and have tried to below code to get date format;

               1- string RcvOn = DateTime.Parse((row.Cells[7].FindControl("txtRcvOn") as TextBox).Text).ToString("dd-MM-yyyy");
               2- DateTime dt = new DateTime();
               3- dt = DateTime.ParseExact(txtRcvOnn.Text, "yyyy/MM/dd", null);
               4- string txtRcvOn = Convert.ToDateTime(txtRcvOnn).ToString();
               5- string txtRcvOn = Convert.ToDateTime(txtRcvOn0.Text).ToString();
               6- DateTime txtdate = DateTime.ParseExact(txtRcvOnn.Text, "MM/dd/yy", null);
               7- string txtRcvOn = Convert.ToDateTime(txtRcvOn0.Text).ToString("dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
               8- int txtRcvOn = Convert.ToInt32(row.Cells[7].Text);
               9- string txtRcvOn = GridView1.Rows[0].Cells[7].Text.ToString();

But all code are given ERRORS i.e. String was not recognized as a valid DateTime. and in some codes the date save as 01/01/1900. How can I fix this???



Solution 1:[1]

If you make your control invisible (Visible="false") the control won't be rendered.
Use <asp:HiddenField>:

<asp:HiddenField runat="server" ID="txtRcvOn" />

If you cannot use <asp:HiddenField>, use the following:

<input type=“hidden” runat=“server” id=“hdnControl” Value=“2” />

If you confirm you get data from your field then try this to convert string to datetime: you will get exception if there is no valid DateTime in Textbox.

DateTime myDate= Convert.ToDateTime(txtRcvOnn.Text);

or you can use this:

DateTime myDate;
if (!DateTime.TryParse(txtRcvOnn.Text, out myDate))
{
    myDate = DateTime.Now; //If failed date time will be current date
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1