Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
3.20/5 (2 votes)
See more:
Hi!! I am new in asp.net (VB)

I want to enter date in SQL Server 2008, I am using Date data type in Database. In ASP.Net(Visual Studi 2010) I want to input date through textbox named txtDOB I have also used calendar with it.... when i manually input date like 21/10/1977 and press submit button it gives me error.

I have used following code:

ASP.NET
<asp:TextBox ID="txtDOB" runat="server" MaxLength="10" Width="90px" 
ToolTip="Enter Date of Birth" TabIndex="9" 
OnTextChanged="txtDOB_TextChanged" BorderColor="Gray" 
BorderStyle="Solid" AutoPostBack="True" >


in VB i used following code behind Save button

VB
Tcmd.Parameters.Add(New SqlParameter("@DOB", Data.SqlDbType.DateTime))

Tcmd.Parameters("@DOB").Value = CDate(Convert.ToDateTime(txtDOB.Text))


Can anybody help me how should i resolve this matter..???
Posted
Updated 28-Mar-14 8:32am
v2
Comments
Richard C Bishop 28-Mar-14 13:44pm    
What is the error?

VB
Convert.ToDateTime((txtDOB.Text),"dd/MM/yyyy")
 
Share this answer
 
If you allow users to enter date via a text box control, then you have to constantly worry about the validity of date value and format that they enter. The format that you gave: "19/10/1977" is not recognized as valid date in .net, let alone passing it to the sql. See the example below:
Imports System
Imports System.Globalization
				
Public Module Module1
	Public Sub Main()
		
		Dim datestring AS string = "19/10/1977"
		Dim dt AS Date    
		If Date.TryParse(datestring, dt)
			Console.WriteLine("date string is valid")
		Else
			Console.WriteLine("date string is NOT valid")
		End If
		
	End Sub
	
End Module

The TryParse method will try to converts the specified string representation of a date and time to its DateTime equivalent, and returns a value that indicates whether the conversion succeeded. In your case, it failed. If you change the datestring to "1977/10/19", then it works. But do you have to go to all these troubles?
My advice is use a Calendar control provided by ASP.NET which will automatic return a valid date value that the user picks and can be inserted directly into any sql parameter without fuss. Refer: asp.net_calender[^]
 
Share this answer
 
v3
hello... see here simple example

DateTime now = DateTime.Now;
                 string rnow = "dd/MM/yyyy";// here you can set date formats
                 var rvar = (now.ToString(rnow));
 
Share this answer
 
use maskededit extender

this control won't allow the user to change the format


C#
<asp:textbox id="txtbox" runat="server" cssclass="textbox" width="150px" xmlns:asp="#unknown"></asp:textbox> <asp:calendarextender xmlns:asp="#unknown">
                    ID="CalendarExtender1" Format="dd/MM/yyyy" TargetControlID="txtbox" runat="server">
                </asp:calendarextender>
                <asp:maskededitextender id="MaskedEditExtender2" targetcontrolid="txtbox" masktype="Date" mask="99/99/9999" runat="server" xmlns:asp="#unknown">
                </asp:maskededitextender>
 
Share this answer
 
buddie you dnt have to do this if you want to see that your code is proper then just write

ASM
Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        TextBox1.Text = Calendar1.SelectedDate
    End Sub
End Class



this code is for just checking whether you are getting correct date or not.
then on some Submit(button) event save value in database
or directly you can save date in database by using GetDate() function in insert query where data will be inserted into database without manually taking date from user.
 
Share this answer
 
Default format of the DateTime is MM/dd/yyyy.

You are providing input in the dd/MM/yyyy.

So before converting into the datetime you should convert the user input date time format to the MM/dd/yyyy and then you should typecast.


C#
string date = "21/10/1977";
string[] dates = date.Split('/');

DateTime dtt = DateTime.Parse(string.Format("{0}/{1}/{2}", dates[1], dates[0], dates[2]));



Thanks
 
Share this answer
 
here is the sample code while designing the text box with date control and format:

Try like this it may help you

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="CC1" %>

<asp:TextBox ID="TXTValidFrom" Enabled="false" runat="server" CssClass="HtmlTxt"   onblur="javascript:checkdate('TXTValidFrom');"Width="170px" TabIndex="33"></asp:TextBox>
 <asp:ImageButton runat="Server" ID="ImageButton3" ImageUrl="~/AppImages/calbtn.gif"
AlternateText="Click to show calendar" Height="16px" Width="16px" TabIndex="33" />
<CC1:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="TXTValidFrom"
PopupButtonID="ImageButton3" Format="dd/mm/yyyy">
</CC1:CalendarExtender>



Script for check date:

C#
function checkdate(sender) {
    var datevalue = document.getElementById(sender).value.trim();
    if (datevalue != '') {
        if (datevalue.length == 6) {
            var today = new Date();
            var todayYear = today.getFullYear();
            var i, j, Day = '', Month = '', Year = '', AYear = '';

            for (j = 0; j < String(todayYear).length; j++) {
                if (j == 0 || j == 1) {
                    AYear = AYear + String(todayYear).charAt(j);
                }
            }
            for (i = 0; i < datevalue.length; i++) {
                if (i == 0 || i == 1) {
                    Day = Day + datevalue.charAt(i);
                }
                if (i == 2 || i == 3) {
                    Month = Month + datevalue.charAt(i);
                }
                if (i == 4 || i == 5) {
                    Year = Year + datevalue.charAt(i);
                }
            }
            datevalue = Day + "/" + Month + "/" + AYear + Year;
            document.getElementById(sender).value = datevalue;
        }
        if (datevalue.indexOf('/') > -1 && (datevalue.length > 6 && datevalue.length == 10)) {
            if (!isDate(datevalue)) {
                document.getElementById(sender).focus();
                document.getElementById(sender).select();

            }
        }
        else {
            alert("The date format should be : ddmmyy Or dd/mm/yyyy");
            document.getElementById(sender).focus();
            document.getElementById(sender).select();
            return false;
        }
    }
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900