Friday, March 30, 2012

Help In Coding

Dim objConn As New SqlConnection
Dim objCmd As New SqlCommand
Dim Value As String = EventCmb.SelectedItem.ToString()
objConn.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Documents and Settings\HP\My Documents\Visual Studio 2005\WebSites\FYP2\App_Data\Event.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True"
Try
objConn.Open()
objCmd.Connection = objConn
objCmd.CommandType = CommandType.Text
objCmd.CommandText = "SELECT EventTel FROM Event WHERE (EventID = @.Value)" ' See how i changed Value to @.Value. This is called a Named Parameter
objCmd.Parameters.AddWithValue("@.Value", Value) ' Add the @.value withthe actual value that should be put. This makes it securer
Dim RetVal As Object = objCmd.ExecuteScalar() ' This returns the First Column of the first row regardless of how much data is returned.
If Not ((RetVal Is Nothing) Or (RetVal Is DBNull.Value)) Then
ContactLbl.Text = RetVal.ToString()
Else
' noting was returned
End If
Catch ex As Exception
Throw ex
Finally
objConn.Close()
End Try

There's an error for in line "Dim RetVal As Object = objCmd.ExecuteScalar() "

Error Message is as follow"Conversion failed when converting the nvarchar value 'LTA' to data type int."

It is due to "ExecuteScalar() "can only store int? I just need to display one data, andValue data comes form a combo box "EventCmb", which i wanted to find the selected String, compared to the "Event" database to get the "EventTel" data How do i solved this problem, any advice? Thanks!

In your code

Dim Value As String = EventCmb.SelectedItem.ToString()

you defined Value as a string, but in our sql

"SELECT EventTel FROM Event WHERE (EventID = @.Value)"

EventID look like a int, this is where the convering error come from

Hope this help

sql

No comments:

Post a Comment