cannot convert string to date - asp.net

Hello stack overflow residents! this is my first post and i'm hoping to receive some help.
I've searched but because I'm still very new, i was not able to full find/understand my answer.
I keep encountering this error:
Message: Conversion from string "" to type 'Date' is not valid. File:
~/reports/pendingshipments.aspx Function: btnExportXls_Click Stack
Trace: at
Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String
Value) at reports_default.btnExportXls_Click(Object sender, EventArgs
e) in C:\Users\jet.jones\Documents\ERIRoot\ERITitan\ERITitan.ssa\Web
Application\reports\pendingshipments.aspx.vb:line 75
Here is my code:
on App_code
**Public Function Reports_PendingShipments(ByVal intClientID As Integer, ByVal strMinDate As Date?, ByVal strMaxDate As Date?, ByVal xmlSiteID As String) As DataTable
'=================================================================================
' Author: Jet Jones
' Create date: 2013.05.28
' Description: Returns a data table with pending shipments for the sites specified
'=================================================================================
Dim objConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Titan").ToString)
Dim cmdGet As New SqlCommand("spReports_PendingShipments", objConn)
Dim parClientID As New SqlParameter("#ClientID", SqlDbType.Int)
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
Dim parSiteID As New SqlParameter("#Sites", SqlDbType.Xml)
Dim objAdapter As New SqlDataAdapter(cmdGet)
Dim objTable As New DataTable
parClientID.Value = intClientID
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
parSiteID.Value = xmlSiteID
'set up the command object
cmdGet.Connection = objConn
cmdGet.CommandType = CommandType.StoredProcedure
'add the parameters
cmdGet.Parameters.Add(parClientID)
cmdGet.Parameters.Add(parMinDate)
cmdGet.Parameters.Add(parMaxDate)
cmdGet.Parameters.Add(parSiteID)
'open the connection
objConn.Open()
'execute the query and fill the data table
objAdapter.Fill(objTable)
'return the data table
Reports_PendingShipments = objTable
'clean up
objConn.Close()
objConn = Nothing
End Function**
my aspx.vb page calls this function this way (Get the values from the query):
objTable = Reports_PendingShipments(ucClientSearch.Value,
txtMinDate.Text, txtMaxDate.Text, strSites)
I'm passing the variable strSites because the website permissions allow for users to have access to one or more site locations, and if a report is run and the user selects "All Sites" from the dropdown, I only want to send the sites they have permissions to via XML.
If I'm missing any information please let me know!
anyone's prompt response is so greatly appreciated.

The problem is that your code is expecting empty dates to be NULL, it doesn't check for empty strings. You need something like this:
if len(strMinDate)=0 then
strMinDate = "01/01/1980"
end
Not sure what you want to default the minimum date to, but you need to add code similar to the IF statement above
Be sure to add this code prior to using the variable a few lines later...

First of all, you adding MaxDate parameter twice:
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
And moreover, then you setting parameters values wuthout check for HasValue:
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
Remove these lines and fix min date parameter name

Related

'Initializing data table before use'

how can i solve this please ?
i am doing a simple database project and i have a search field i wrote the following code for searching and displaying data in DataGridView but the
Null Reference Exception keeps showing up because i'm initializing the table with nothing and yet if i don't do so i get 'Used Before Initializing warning.
the question is :how can i initialize the table properly .
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim searchText As String = txtSearch.Text
Dim matchText As String = ""
Dim rowMatch As Boolean = False
Dim foundRows As DataTable = Nothing 'this initializig causes the problem of null exception,But how can i Initialize it then?????
For Each rw As DataRow In dataSet.Tables(0).Rows
Dim cl As String = rw.Item(1).ToString ' this cell is FirstName Cell
If searchText.Length > cl.ToString.Length Then
matchText = cl.ToString
Else
matchText = cl.ToString.Substring(0, searchText.Length)
End If
'bellow it adds the Found Row (rw) to the table
If (searchText.Equals(matchText) And searchText <> "" And Not foundRows Is Nothing) Then foundRows.Rows.Add(rw)
Next
'to shows data if the search text field is not empty then show the found matching rows
If (searchText <> "") Then
contactView.DataSource = foundRows
Else ' else show the original tavle again
contactView.DataSource = dataSet.Tables(0)
End If
contactView.Refresh() 'refresh
End Sub
here is the screenshot of the form
i tried to use
Dim foundRows As DataTable = New DataTable
but it shows ArgumentException
This Row already belongs to another Table
i also tried this
but as you can see nothing works please Help !
Yes
i finally got it
i was having a problem in columns
Dim foundRows As DataTable = New DataTable("PseuContact") 'this initializig causes the problem of null exception,But how can i Initialize it then?????
foundRows.Columns.Add("ID")
foundRows.Columns.Add("First Name")
foundRows.Columns.Add("Last Name")
foundRows.Columns.Add("Phone Number")
foundRows.Columns.Add("Mobile Number")
foundRows.Columns.Add("Email Address")
initializing columns is important when declaring new table
this's been the best

How to select GUID column by another GUID column in VB.net?My Select query does not work

I am new to programming and get the chance to work and maintain in another developers project.
The project is built with ASP.Net Vb.Net and SQl Server.
I am trying to select the primary key ID (which is actually a GUID) from a table.
SQID = Core.DB.GetString("SELECT id FROM SQC WHERE sid = " & sid)
In the Table SQC the primary key is id which is guid and the sid is also guid which is primary key to another table.
my previous developer developed the code to select string variable GetString function where GetString is
Shared Function GetString(ByVal selectQueryText As String, ByVal ParamArray params As SqlParameter()) As String
Dim dt As DataTable = Nothing
Try
dt = GetData(selectQueryText, CommandType.Text, params)
If dt.Rows.Count = 0 Then
Return ""
Else
If TypeOf dt.Rows(0)(0) Is DBNull Then
Return ""
Else
Return CStr(dt.Rows(0)(0))
End If
End If
Finally
If dt IsNot Nothing Then dt.Dispose()
End Try
End Function
When I debug the code my process enters into GetString Function and from Get String it goes to GetData function
Shared Function GetData(ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataTable
Dim conn As SqlConnection = Nothing
Try
conn = GetOpenSqlConnection()
Return GetData(conn, selectCommandText, selectCommandType, params)
Finally
If conn IsNot Nothing Then conn.Dispose()
End Try
End Function
Shared Function GetData(ByVal conn As SqlConnection, ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataTable
If conn Is Nothing Then Return GetData(selectCommandText, selectCommandType, params)
Dim sa As SqlDataAdapter = Nothing
Try
sa = New SqlDataAdapter(selectCommandText, conn)
sa.SelectCommand.CommandType = selectCommandType
Dim dt As New DataTable
Try
For Each param As SqlParameter In params
sa.SelectCommand.Parameters.Add(param)
Next
sa.Fill(dt)
Return dt
Catch ex As Exception
dt.Dispose()
Throw ex
End Try
Finally
If sa IsNot Nothing Then sa.Dispose()
End Try
End Function
In the Try Catch area of exeption handling the code breaks and throws the exception error. It saying Incorrect syntax near 'a379'. which is first the part of sid (GUID). I mean the sid value is 9417A379-6371-432F-9DA5-BCFC46DD95A1
I am not sure how to handle this. I want to select the id from from SQC table and store it in a variable.
I am looking for your advice and suggestion. As I am new in the programming world please also point me my mistakes.
Thanks
It looks like your issue could be fixed like so:
SQID = Core.DB.GetString("SELECT id FROM SQC WHERE sid = '" & sid & "'")
But you should be aware that this style of code is open to SQL injection and you may want to look at ways of parameterising your queries (i.e. don't take what's in this project as good practice).

Error: "No value given for one or more required parameters" on UPDATE query from ASP.NET

I receive the error
No value given for one or more required parameters
when I try to execute the following code
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t2 = TextBox2.Text
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand("UPDATE login1 SET height ='" + TextBox2.Text + "' WHERE username =" + str, dbcon) //This is the part where the error is ....
dbcon.Open()
dbcmd.ExecuteNonQuery()
dbcon.Close()
End Sub
End Class
I've tried making changes in this statement like using different methods with parameters...but all the code shows the same error.
Using a parameterized query is definitely the way to go, but using named parameters should be discouraged in this context because OleDbCommand objects ignore the parameter names when the CommandType is Text. They only rely on the order in which the parameters appear in the CommandText (ref: here).
Therefore, the preferred approach would be
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height=? WHERE username=?",
dbcon)
dbcmd.Parameters.AddWithValue("?", TextBox2.Text) ' height
dbcmd.Parameters.AddWithValue("?", str) ' username
dbcmd.ExecuteNonQuery()
End Using
You don't supply the user name properly at the end of the query. But that's not the only problem here. Let me edit the code a bit:
Using dbcon As New OleDbConnection(cString)
dbcon.Open()
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height = #height WHERE username = #username",
dbcon)
dbcmd.Parameters.AddWithValue("#height", TextBox2.Text)
dbcmd.Parameters.AddWithValue("#username", str)
dbcmd.ExecuteNonQuery()
End Using
End Using
NOTE: the using statement to ensure the objects are disposed property and also, do not share connections. When you need a connection, build it, open it, use it, and dispose it.

webform multi column single row SQL Server result to vb variables

Ive looked through a few questions on here today and think I'm going round in circles.
My webform has a number of elements including username which is a drop down list (populated by a SQL statement)
On submit of the form i would like the code behind aspx.vb file run a select top 1 query and return a single row of data with 4 columns.
The returned SQL query result 4 columns would only be used later in the aspx.vb file so i want to assign each of the columns to a variable. I'm struggling with this task and assigning the variable the column result from the query.
Protected Sub submitbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbtn.Click
Dim connString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim conn As New SqlConnection(connString1)
Dim sql1 As String = ""
Dim col1h As String = ""
Dim col2r As String = ""
Dim col3title As String = ""
Dim col4UQN As String = ""
sql1 = "SELECT TOP 1 col1h,col2r,col3title, col4UNQ from tblDistinctUserOHR where colID_Username= '" + username + "' "
Dim cmd1 As New SqlCommand(sql1, conn)
'open the connection
'run the sql
'the result will always be found but in case its not some form of safety catch (the variables stay as empty strings
'assign the results to the variables
'close connections
'lots of other code
End Sub
could someone point me in the right direction to run the SQL and assign the result to the the variables. I've been reading about ExecuteScalar() and SqlDataReader but that doesn't seem to be the correct option as the only examples I've found handle a single result or lots of rows with a single column
Thanks for any samples and pointers.
Try this:
Dim da As New OleDb.OleDbDataAdapter(sql1, conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count < 0 Then
col1h = dt.Rows(0).Item("col1h")
col2r = dt.Rows(0).Item("col2r")
col3title = dt.Rows(0).Item("col3title")
col4UQN = dt.Rows(0).Item("col4UQN")
Else
'No rows found
End If

How can I make the logged-In name the default option in dropdownlist box?

Experts.
When a user logs into one of our web apps, there is a dropdownlist containing the names of all of our employees.
An employee could log into the system to record his or her entries into the database.
The employee could log the entries for another employee.
So far, an employee has had to select his or her name from the dropdown list and we don't want employees typing their names, just for consistency and to preserve data integrity.
Our problem currently is how to have employee's login name become the default option in the dropdown. The employee can select another name from the list if making the entries for another empployee.
Any ideas how to accomplish this task?
Thanks alot in advance.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim s As String
Dim reader As OleDbDataReader
txtFullName.Text = Session.Item("assignedTo").ToString
'Initialize Connection
s = "Select login_id, UserName from tblusers ORDER BY UserName"
Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
'Open the connection
conn.Open()
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
txtLoginName.DataSource = reader
txtLoginName.DataValueField = "login_id"
txtLoginName.DataTextField = "UserName"
txtLoginName.DataBind()
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
End If
End Sub
<--new code -->
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
Dim currentUserName As String = ""
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserName)) Then
currentUserName = reader("UserName").ToString()
End If
End While
txtLoginName.SelectedValue = currentUserName
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
you can use Page.User property to get the Name and then assign it to the dropdown's selected Value on Page_Load event.
Could you just simply select it by text after you populate the list? I assume you'll know the login_id once the user logs in, so you could find the username from the results of the query, like so:
UNTESTED:
string currentUserName = "";
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserLogin)) Then
currentUserName = reader("UserName").ToString()
End If
End While
And then, once the list is populated via the results, select the correct user by username.
txtLoginName.Items.FindByValue(UserName).Selected = true;
Or even better yet, since you should already know the login_id, you can simply select by value from the populated drop down list, like so:
txtLoginName.SelectedValue = login_id
It's worth noting that this is making a very big assumption that the login_id will exist in the list. You may want to perform the appropriate check first to see if the login_id exists before selecting.
If you are using forms or windows authentication, wouldn't you just use:
txtLoginName.Text = User.Identity.Name
I believe this will select it if the text is in the list and matches exactly. Or, just use Sam's method. But was it the User.Identity.Name that you were looking for?

Resources