Convert ASP.NET textbox control .text contents to Date/Time format - asp.net

I am trying to insert into a database - various details about an event. The asp.net textbox is using the Calendar Extender (so a little calendar pops up and fills the textbox with a correctly formatted date). The EventDate field in my Access database is of the type Date/Time. I need to convert the text/string to date/time format
I have tried this so far:
VB:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
(#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
Dim strDate As String = tb_eventdate.Text
Dim dtfi As New System.Globalization.DateTimeFormatInfo
dtfi.ShortDatePattern = "dd/MM/yyyy"
dtfi.DateSeparator = "/"
Dim objDate As DateTime = Convert.ToDateTime(strDate, dtfi)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_eventtitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_eventdescription.Text)
cmd.Parameters.AddWithValue("#f3", tb_eventdate.Text)
cmd.Parameters.AddWithValue("#f4", dd_eventcategory.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/calendar.aspx")
End Sub
Here is my clientside code just for reference:
<h1>Add An Event!<ajaxToolkit:ToolkitScriptManager
ID="ToolkitScriptManager1"
runat="server">
</ajaxToolkit:ToolkitScriptManager>
</h1>
<p>Title of Event:
<asp:TextBox ID="tb_eventtitle" runat="server"></asp:TextBox>
</p>
<p>Event Description:
<asp:TextBox ID="tb_eventdescription" runat="server"></asp:TextBox>
</p>
<p>Event Date:
<asp:TextBox ID="tb_eventdate" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" runat="server"
TargetControlID="tb_eventdate">
</ajaxToolkit:CalendarExtender>
</p>
<p>Event Category:
<asp:DropDownList ID="dd_eventcategory" runat="server"
DataSourceID="SqlDataSource1" DataTextField="CategoryTitle"
DataValueField="CategoryTitle">
</asp:DropDownList>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</p>
When I try to fill out the form, I receive this error:
My Two questions are:
What is wrong with the code above, and how do I successfully use the DateTimeFormatInfo class to convert String to Date/Time?
On a side note, the Calendar Extender inputs the date into the textbox in American Time format (MM/DD/YYYY), how do I change this to British (DD/MM/YYYY) format (I couldn't see an obvious property in the properties dialog to do this?)
Thanks in advance for your answers!
Adam
EDIT: Updated code below:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
(#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_eventtitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_eventdescription.Text)
cmd.Parameters.AddWithValue("#f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture))
cmd.Parameters.AddWithValue("#f4", dd_eventcategory.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/calendar.aspx")
End Sub

I'd recommend you use DateTime.ParseExact static method, especially this oveload:
DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",CultureInfo.InvariantCulture)
This will parse the text you have by the concrete format you specify ("dd/MM/yyyy" currently, case is important since mm is minutes as opposed to MM being months). Use of CultureInfo.InvariantCulture guarantees that date separators will be retrieved from the format string (the second parameter). I have noticed that if current culture is used, it overrides some aspects of the format string you pass to ParseExact.
A note on CultureInfo
Invariant culture is good also for the reason that your local dev environment may have different regional information setup than the deployment environment. Usually, .NET uses the current culture in all .ToString calls and implicit formatting or parsing. When forcing a format and culture invariance explicitly, you are less prone to problems you cannot reproduce locally but exist on the production application.
A note on date/time formats
With exact parsing, the datetime format is expected to strictly match the format of the input. You should then take into consideration the following examples:
dd matches two-digit days only. So "dd/MM/yyyy" it will match "01/01/2013", but will fail for "1/1/2013" because it expects the exact number of digits for the day part. If you do not want leading zeros use: d/M/yyyy instead. Single letter means one digit for days less than 10 and two digits for the others.
MM matches two-digit month, so all that applies to dd vs. d is the same for months.
yyyy expects the year to be in 4 digits. If you use two-digit year, use yy instead.
A note on some ADO.NET providers
As it turns out to be the case with MS Access, the correctly parsed date-time object is not sufficient to make the query work. Currently, the following code
cmd.Parameters.AddWithValue(...)
is used to add parameters to the query. However, this approach omits passing information to the ADO.NET db provider that tells what database type to use for the parameter. I have read on some forums that MS Access/OleDb is not capable to resolve the correct type in all cases. Therefore I recommend the following approach:
Dim prm as OleDbParameter = _
New OleDbParameter("#dateTimeParameterName", OleDbType.DateTime)
prm.Value = value 'value is an instance of `System.DateTime` parsed
'from the input
cmd.Parameters.Add(prm)
The above code allows to specify the parameter database type explicitly, so the OleDb driver is now capable of correctly passing the DateTime object to the MS Access database.

I used below short code:
//myDateValue is System.DateTime object.
OleDbCommand commandObject = new OleDbCommand();
...
commandObject.Parameters.Add(new OleDbParameter("#ADDED_DATE_PARAM", OleDbType.Date).Value = myDateValue);

Related

VB.NET Connection string ADODB Connection (Web.Config)

I write the code below to connect database using web config but cannot connect database using ADODB to fetch data from database into textboxes
Webconfig
<connectionStrings>
<clear />
<add name="constr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CustomerInfor.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>
SearchButton
Dim consString As String = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim objConn As New OleDbConnection(consString)
objConn.Open()
Please help with right code to fetch data from database into textboxes
Thanks
Ok, lets try this a bit different.
First up: Lets get the connection string OUT side of the code.
Like for desktop, or anything else? You can add values like connection string to the project like this:
And really nice is you get to use the connection builder to do this.
The above setting are shoved into web.config for you automatic.
So, setup your connection in above.
Ok, now in this case, I just shove on the screen a few text boxes for a user and hotel name.
Real plane jane like this:
<div style="width:25%;text-align:right;padding:25px;border:solid;border-width:1px">
<style> .tbox {width:260px;margin-left:5px;margin-bottom:15px;border-radius:8px;border-width:1px}</style>
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" class="tbox"/>
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" class="tbox" />
<br />
Last Name:<asp:TextBox ID="txtLast" runat="server" class="tbox"/>
<br />
City: <asp:TextBox ID="txtCity" runat="server" class="tbox"/>
<br />
Active:<asp:CheckBox ID="ckActive" runat="server" />
<br />
<br />
Ok, now our code to load this. I don't have a text box or source for the id, but a integer value OR a text value will work.
So, our code to load up is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Dim cmdSQL As OleDbCommand = New OleDbCommand()
cmdSQL.CommandText = "SELECT * from tblhotels where ID = #ID"
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = 23
Dim rst As DataTable = MyRst(cmdSQL)
With rst.Rows(0)
txtHotelName.Text = .Item("HotelName")
txtFirst.Text = .Item("FirstName")
txtLast.Text = .Item("LastName")
txtCity.Text = .Item("City")
ckActive.Checked = .Item("Active")
End With
ViewState("rst") = rst
End Sub
Note the cute helper routine MyRst.
So, you can use that routine EVERY where. eg:
Dim cmdSQL As OleDbCommand = New OleDbCommand("select * from RoomTypes")
Dim rst as DataTable = MyRst(cmdSQL)
So, it just a handy dandy routine. (you do NOT have to use parameters if you don't need them).
Ok, so we loaded the one row into the table (and we save that row for later use into ViewState)
Ok, so now we see this:
Now, the save code. Note how we used a record set (datatable) in place of a GAZILLION parameters.
We do this for quite a few reasons.
Strong data type conversion occurs here.
Parameter order for the save does not matter. I can cut-paste, or add 5 or 15 more columns here, and it works - and order does not matter!!!
So, now the save code.
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
SaveData()
End Sub
Sub SaveData()
Dim rst As DataTable = ViewState("rst")
Using con As New OleDbConnection(My.Settings.AccessTest2)
Using cmdSQL As New OleDbCommand("SELECT * from tblHotels WHERE ID = 0", con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdSQL)
Dim daSQLU As OleDbCommandBuilder = New OleDbCommandBuilder(da)
con.Open()
With rst.Rows(0)
.Item("HotelName") = txtHotelName.Text
.Item("FirstName") = txtFirst.Text
.Item("LastName") = txtLast.Text
.Item("City") = txtCity.Text
.Item("Active") = ckActive.Checked
End With
da.Update(rst)
End Using
End Using
End Sub
NOTE: not a bug, I MOST certainly did use where ID = 0
So, the nice part is we can add more text box etc. We will have to add code to setup the text boxes, but at least the order don't matter.
Last but not least?
That helper routine, the one I use to fill datatables. I even use it for say filling out combo box (dropdown lists), or whatever.
Public Function MyRst(cmdSQL As OleDbCommand) As DataTable
Dim rstData As New DataTable
Using MyCon As New OleDbConnection(My.Settings.AccessTest2)
cmdSQL.Connection = MyCon
MyCon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
Return rstData
End Function
So note how we used the connection string setting that we setup in the project.
And since access is sensitive to parameter order, then I adopted the above idea of using a data table. Note that this approach also works for a grid, or even adding rows. When you run that update routine? rows added, rows edits, row deleted?
They all are done for you with the ONE da.Upate(rst).
Note also, you should set your project to run as x86, and not x64, since JET ONLY can work as x32. However, the ACE data engine can be had for x64 bits.

Sql table check

I have a table with the following fields ID IDuser IDpc FROM TO.
obviously a PC cannot be used during the same time period by more than one user. how do i place a constraint on entries so that incorrect entries are prevented?
I use sql Server 2016 (management studio) with asp.net
ok, as noted, I though the part about multiple users using the same PC had to do with multi-user databases!
I now see that you are booking a PC to be used, and you don't want booking collisions.
Ok, there is a VERY neat condition to test/check for a booking collision.
It looks like this:
A collision occurs when:
RequestStartDate <= EndDate
and
RequestEndDate >= StartDate
And if the values include date + time, then the above still works just fine.
The above condition will find ANY kind of overlap (so a date/time in the middle) or any parts that overlap.
As I suggested in comments? You could get/have the data base not allow you to add that row (you would have to use a table trigger).
However, then what?
What this REALLY suggests? You don't write out the record and expect a database failue. Worse yet, you really want to give the user some nice feed back.
So, your booking page would ask for the room, and then the start/end time (with date). You use the above condition, and if record(s) are returned, then you tell the user they can't book the room. However, if no matches occur, then you add that row to the database.
This kind of problem actually seems quite difficult, but it turns out with the above simple condition, is is remarkable simple.
Lets do this simple example as a asp.net webforms.
So, drop in a list box, two text boxes (start/end) and a book button.
So, the markup looks like this:
<div style="margin-left:40px">
<h2>Book a work station</h2>
<div style="float:left">
<h3>Select a work station</h3>
<asp:ListBox ID="lstCompter" runat="server"
DataTextField="Computer" DataValueField="ID" Height="151px" Width="294px"></asp:ListBox>
</div>
<div style="float:left;margin-left:20px">
<div style="float:left">
<h3>Start Time</h3>
<asp:TextBox ID="txtStart" runat="server" TextMode="DateTimeLocal"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<h3>End Time</h3>
<asp:TextBox ID="txtEnd" runat="server" TextMode="DateTimeLocal"></asp:TextBox>
</div>
<div style="clear:both;float:left;margin-top:40px">
<asp:Button ID="cmdBook" runat="server" Text="Book Room" />
</div>
<div style="clear:both;float:left">
<br />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
I tossed in a few divs to lay this out.
Ok, now the code to load up the listbox was this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Using cmdSQL As New SqlCommand("SELECT ID, Computer from Computers ORDER BY Computer",
New SqlConnection(My.Settings.TEST4))
cmdSQL.Connection.Open()
lstCompter.DataSource = cmdSQL.ExecuteReader
lstCompter.DataBind()
End Using
End Sub
And now we get this:
Note that if you drop in that textbox and in the property sheet choose DateTimeLocal as the format, then without any extra code, you get that way cool date = time picker for free.
Now, lets write the code to check for if we can book.
The user selects a room, and then the start/end times (that could be for 1 hour, or one 1 week - it don't matter.
So, now our book button code looks like this:
Protected Sub cmdBook_Click(sender As Object, e As EventArgs) Handles cmdBook.Click
Dim strSQL As String
strSQL = "SELECT * FROM Bookings WHERE IDPc = #IDpc " &
"AND #RequestStart <= [TO] " &
"AND #RequestEnd >= [From] "
Using cmdSQL As New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST4))
cmdSQL.Parameters.Add("IDpc", SqlDbType.Int).Value = lstCompter.SelectedItem.Value
cmdSQL.Parameters.Add("#RequestStart", SqlDbType.DateTime).Value = txtStart.Text
cmdSQL.Parameters.Add("#RequestEnd", SqlDbType.DateTime).Value = txtEnd.Text
cmdSQL.Connection.Open()
Dim rstBooking As New DataTable
rstBooking.Load(cmdSQL.ExecuteReader)
If rstBooking.Rows.Count > 0 Then
' booking not allowed - show message
lblMsg.Text = "Computer station already booked - try differnt date/time"
Else
' add this booking
Dim da As New SqlDataAdapter(cmdSQL)
Dim daupdate As New SqlCommandBuilder(da)
Dim OneRow As DataRow = rstBooking.Rows.Add
OneRow("IDpc") = lstCompter.SelectedValue
OneRow("IDUser") = LogOnID
OneRow("From") = txtStart.Text
OneRow("To") = txtEnd.Text
da.Update(rstBooking)
lblMsg.Text = "Room booked!"
End If
End Using
End Sub
Note how simple this becomes. In about the SAME time it took me to write this post? I in fact have a real working booking page. It would need more love an care then a quick dirty example like above, but all in all, it is remarkable that the above works.
our Computers (table) to book for the list box was this:
And then the booking table of course is this:
And that is quite much it. You can see we query the database, and if we find a match (collision), then we NEVER even try to add the row, and we give a user that message.
But, if now rows are found, then we add the row to the database.
So, it will look like this:
It is times like this that one realizes how amazing simple this was in asp.net.
Enjoy!
FYI: both "to" and "from" are SQL words - you have to use [To] and [From] (brackets around) those words, since SQL server will get confused - those column names are what we call reserved words - and "FROM" is part of regular sql syntax, so just remember to use those [] around the sql.

String to Date conversion

Hi I am receiving an error of string to date conversion
here's my script
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
dim oVal as New Collections
'Time stamp
oVal.Add(DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", Nothing), "ofield_starttime")
oVal.Add(dt.ToString("dd-MM-yyyy HH:mm:ss"), "ofield_stoptime")
Savetime(oVal)
and under public function saveTime(oVal as Collection)
Dim sQuery As New SqlCommand
sQuery.CommandType = CommandType.StoredProcedure
sQuery.CommandText = "PSC_Timestamp"
With sQuery.Parameters
.AddWithValue("#PSCStart", Convert.ToDateTime(oVal("ofield_starttime")))
.AddWithValue("#PSCStop", CDate(oVal("ofield_stoptime")))
End With
sQuery.Connection = myConnection
If myConnection.State = 1 Then 'check if connection open
myConnection.Close()
End If
myConnection.Open()
sQuery.ExecuteNonQuery()
myConnection.Close()
I am receiving this error
Conversion from string "13-07-2015 13:09:38" to type 'Date' is not valid.
A helping hand is highly appreciated...thanks in advance.
The problem is you don't specify where your error is happening. If it's the following line:
DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", Nothing)
... then what I find interesting is that you are passing Nothing to the final IFormatProvider provider parameter. When you do that, it defaults to the current culture. Is it possible that your current culture is messing up how the data is being parsed?
To ensure consistent behavior, try passing CultureInfo.InvariantCulture instead:
DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
If your error is happening with the following lines:
.AddWithValue("#PSCStart", Convert.ToDateTime(oVal("ofield_starttime")))
.AddWithValue("#PSCStop", CDate(oVal("ofield_stoptime")))
Then, make sure to change the date conversion logic to use DateTime.ParseExact and you should be fine.
I found out - to rectify this scenario I have to set the calendar format to a desired settings that has the same format that I am using with my application. This resolved the issue of error in date conversion.

String was not recognized as a valid DateTime. Existing solutions have not worked for me

I have googled this all morning but could not resolve it.
Infact, the solution I am trying below was extracted from this site:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim eDate As TextBox = DirectCast(e.Row.FindControl("txtEventDate"), TextBox)
eDate.Text = Request.QueryString("evdates")
DateTime.ParseExact(eDate.Text, "MM/dd/yyyy", CultureInfo.CurrentCulture)
End If
The date value displays as 14/04/2014 00:00:00 but we would like to display as MM/dd/yyyy.
But we keep getting String was not recognized as a valid DateTime.
I even tried doing this on the markup but to no avail.
<asp:TextBox ID="txtEventDate" DataFormatString="{0:d}" runat="server"></asp:TextBox>
Any ideas how to fix this?
From your question, it looks like the date is in the format of dd/MM/yyyy. British style. Also you might want to use CultureInfo.InvariantCulture. I am not sure where your IIS server is hosted or what culture is configured on the box.
You can try this:
// read the data from the request
string temp = Request.QueryString("evdates");
// convert the string to datetime object
DateTime d = DateTime.ParseExact(temp, "MM/dd/yyyy", CultureInfo.InvariantCulture);
// format any way you like
eDate.Text = d.ToString("MM/dd/yyyy);

System.ArgumentException: String value can not be converted to a date

I have a web form that uses an Ajax date calendar. This works fine. The problem that i have is that when i submit my form i get the following message.
'String value can not be converted to a date' .AgendaDate = New SmartDate(txtAgendaDate.Text)
Here is my web form that holds the calendar and the associated text box...
<td>
<asp:TextBox ID="txtAgendaDate" runat="server" ForeColor="Black" ></asp:TextBox>
</td>
<td>
<asp:ImageButton runat="Server" ID="ImageButton1" ImageUrl="~/images/calendarpic.png"
AlternateText="Click here to display calendar" />
<cc1:calendarextender ID="CalendarExtender1" runat="server"
TargetControlID="txtAgendaDate" PopupButtonID="ImageButton1" >
</cc1:calendarextender>
</td>
I have a class with the associated properties on it for the web form. The rest of the fields work and submit data to the database except the textfield for the ajax calendar.
Here is my stripped down version for the code for the class and the txtAgendaDate code...
#Region " Agenda Variables "
'Declare Variables and data types and set default values
Private mAgendaID As Integer = 0
Private mOrganiser As String = ""
Private mMeeting As String = ""
Private mAgendaDate As SmartDate = New SmartDate()
#End Region
#Region " Constructors "
Public Sub New()
End Sub
Public Sub New(ByVal reader As SafeDataReader)
' Public Sub New(ByVal reader As SQLDataReader)
'Combine variables & property types
With reader
mAgendaID = .GetInt32("AgendaID")
mOrganiser = .GetString("Organiser")
mMeeting = .GetString("Meeting")
mAgendaDate = .GetSmartDate("AgendaDate")
End With
End Sub
#End Region
#Region "Properties"
'Define form field properies so that they can be used when adding the data to the database on the add button is pressed.
Public Property AgendaID() As Integer
Get
Return mAgendaID
End Get
Set(ByVal Value As Integer)
mAgendaID = Value
End Set
End Property
Public Property Organiser() As String
Get
Return mOrganiser
End Get
Set(ByVal value As String)
mOrganiser = value
End Set
End Property
Public Property Meeting() As String
Get
Return mMeeting
End Get
Set(ByVal value As String)
mMeeting = value
End Set
End Property
Public Property AgendaDate() As SmartDate
Get
Return mAgendaDate
End Get
Set(ByVal Value As SmartDate)
mAgendaDate = Value
End Set
End Property
#End Region
End Class
Here is my command that looks connects to the DB and at the stored procedure and also has the parameters.
Public Class Agenda_TempDAL
Public Shared Function AddAgenda_Temp(ByVal Agenda_Temp As Agenda_Temp) As Integer
'Declare i as integer as 0
Dim iAgendaID As Integer = 0
'Database conn, this is linked to the web config file .AppSettings
Using dbconnection As New SqlConnection(ConfigurationManager.AppSettings("dbconnection"))
dbconnection.Open()
'Command to state the stored procedure and the name of the stored procedure
Using dbcommand As SqlCommand = dbconnection.CreateCommand
With dbcommand
.CommandType = CommandType.StoredProcedure
.CommandText = "Stored_Proc_Name"
'Create parameter for AgendaID and output
Dim oParam As New SqlParameter
oParam.ParameterName = "#AgendaID"
oParam.Direction = ParameterDirection.Output
oParam.SqlDbType = SqlDbType.Int
'Create parameters for the remaining fields
.Parameters.Add(oParam)
.Parameters.AddWithValue("#Organiser", Agenda_Temp.Organiser)
.Parameters.AddWithValue("#Meeting", Agenda_Temp.Meeting)
.Parameters.AddWithValue("#AgendaDate", Agenda_Temp.AgendaDate.DBValue)
'Simply execute the query
dbcommand.ExecuteNonQuery()
End With
End Using
End Using
'Need to return the agendaID as an integer.
Return iAgendaID
End Function
End Class
And here is the code behind the button ion the web page. This is the page that causes the error based on the property / field. The problem lies on this line...
.AgendaDate = New SmartDate(txtAgendaDate.Text)
The whole code for the button is here...
Protected Sub btnAddAgendaTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddAgendaTemplate.Click
'This works alongside the Class named Agenda_Temp which has the properties and DB connection assigned to it for each web form field.
Dim oAgenda_Temp As New Agenda_Temp
'Within the object Agenda_Temp Class use the properties defined.
'They are required to be defined in the Agenda_Temp/ app code so we can use them within here.
With oAgenda_Temp
.Organiser = txtOrganiser.Text
.Meeting = txtMeeting.Text
.AgendaDate = New SmartDate(txtAgendaDate.Text)
'Within the object Agenda_Temp class use the defined DAL which includes all the DC connect and stored procedures.
oAgenda_Temp.AgendaID = Agenda_TempDAL.AddAgenda_Temp(oAgenda_Temp)
End With
End Sub
End Class
I understand that its telling me that the string value cannot be converted to a date but i don't know hoe to resolve this as i am new to .net 2010?
Any help much appreciated.
Convert the string to a date before newing it:
From MSDN:
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Your's would become
DateTime dt = Convert.ToDateTime(txtAgendaDate.Text)
Then pass the date to your SmartDate constructor:
oAgenda_Temp.AgendaDate = new SmartDate(dt)
The final result:
With oAgenda_Temp
.Organiser = txtOrganiser.Text
.Meeting = txtMeeting.Text
.AgendaDate = New SmartDate(Convert.ToDateTime(txtAgendaDate.Text))
'Within the object Agenda_Temp class use the defined DAL which includes all the DC connect and stored procedures.
oAgenda_Temp.AgendaID = Agenda_TempDAL.AddAgenda_Temp(oAgenda_Temp)
End With
As others have pointed out, you need to convert the input value to a DateTime. I don't know what the SmartDate() function is doing, but the error message clearly indicates that the value cannot be converted to a date.
Secondly, I would add some validation to make sure that the input is valid before you submit the page. Use the RequiredFieldValidator and CompareValidator or RegularExpressionValidator:
<asp:TextBox ID="txtDate" runat="server" ... />
<asp:RequiredFieldValidator ID="reqDate" runat="server" ErrorMessage="Required" Display="Dynamic" ControlToValidate="txtDate"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regDate" runat="server" ControlToValidate="txtDate" ErrorMessage="Please enter a valid date in the format (mm/dd/yyyy)" ValidationExpression="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"></asp:RegularExpressionValidator>

Resources