The ConnectionString not initialized - asp.net

Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)

It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?

When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]

Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.

Related

Insert records into Access database produces blank rows

I'm trying to insert records into my Access database using the following code:
<script runat="server">
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbReader As OleDbDataReader
Dim sqlString As String
Sub page_load()
Try
txtFName.Text = ""
txtLName.Text = ""
dbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("MyDatabase.accdb"))
dbConnection.Open()
sqlString = "SELECT * FROM table1 ORDER BY ID"
dbCommand = New OleDbCommand(sqlString, dbConnection)
dbReader = dbCommand.ExecuteReader()
While dbReader.Read()
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & dbReader("F_Name") & " " & dbReader("L_Name") & "<br/><br/>"
lblName.EnableViewState = False
nameArea.Controls.Add(lblName)
End While
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
Sub addToDatabase()
Try
dbConnection.Open()
sqlString = "INSERT INTO table1 (F_Name,L_Name) VALUES (#FName, #LName)"
dbCommand.CommandText = sqlString
dbCommand.Parameters.AddWithValue("#FName", txtFName.Text)
dbCommand.Parameters.AddWithValue("#LName", txtLName.Text)
dbCommand.ExecuteNonQuery()
Finally
dbConnection.Close()
End Try
End Sub
</script>
In my asp code below, I have two TextBoxes to hold first name and last name, as well as a button that will call addToDatabase when clicked, and a placeholder to display each record pulled from the database:
<asp:TextBox ID="txtFName" runat="server" />
<asp:TextBox ID="txtLName" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="addToDatabase" runat="server" />
<br />
<asp:PlaceHolder ID="nameArea" runat="server" />
My access database contains a table named table1, with an ID, F_Name and L_Name field, with their DataTypes being AutoNumber, Text and Text respectively.
My problem is when I click btnSubmit, it adds blank records into my database for F_Name and L_Name instead of what was in the TextBoxes, and continues to add blank records on every browser refresh.
What is going on?
Remove the following lines from your page_load method.
txtFName.Text = ""
txtLName.Text = ""
Add the following at the end of the addToDatabase method. This will then show you the new names in the page without needing a call to the database.
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & txtFName.Text & " " & txtLName.Text & "<br/><br/>"
lblName.EnableViewState = False
nameArea.Controls.Add(lblName)
I moved my code around and added a new Sub that will get names, then called that method on initial page_load and after calling addToDatabase. I kept everything else in the asp below the same.
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbReader As OleDbDataReader
Dim sqlString As String
Sub page_load()
dbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("MyDatabase.accdb"))
dbCommand = New OleDbCommand("", dbConnection)
If Not Page.IsPostBack Then
showNames()
End If
End Sub
Sub showNames()
Try
dbConnection.Open()
sqlString = "SELECT * FROM table1 ORDER BY ID"
dbCommand.CommandText = sqlString
dbReader = dbCommand.ExecuteReader()
While dbReader.Read()
Dim lblName As Label = New Label()
lblName.ID = dbReader("ID")
lblName.Text = "<b>Name: </b>" & dbReader("F_Name") & " " & dbReader("L_Name") & "<br/>"
lblEntry.EnableViewState = False
nameArea.Controls.Add(lblName)
End While
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
Sub addToDatabase(src As Object, args as EventArgs)
Try
dbConnection.Open()
sqlString = "INSERT INTO table1 (F_Name,L_Name) VALUES (#FName, #LName)"
dbCommand.CommandText = sqlString
dbCommand.Parameters.AddWithValue("#FName", txtFName.Text)
dbCommand.Parameters.AddWithValue("#LName", txtLName.Text)
dbCommand.ExecuteNonQuery()
Finally
dbConnection.Close()
End Try
showNames()
End Sub

How do I resolve "Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow' error?

We have a dropdownlist in gridview that gets populated from the database.
There is a also a textbox next to this dropdownlist.
If the option the user is looking for isn't in the dropdown, enter that value into the textbox and when submitted to the database, will now become in the dropdownlist.
I am running into the following error:
Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow'.
The error is on this line:
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
I believe this error occurs because I am using an imagebutton on the markup to submit to the database.
<asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/save.png"
onmouseout="this.src='images/save.png'"
onmouseover="this.src='images/save.png'"
OnClick="btnSave_Click" alt="Save Data" />
Any idea how to resolve this?
Even though this is vb, I welcome solution in c# if available.
Thank you!
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
' Try
SetRowData()
Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)
If table IsNot Nothing Then
For Each row As DataRow In table.Rows
Dim txLName As String = TryCast(row.ItemArray(1), String)
Dim txName As String = TryCast(row.ItemArray(2), String)
Dim txEmail As String = TryCast(row.ItemArray(3), String)
Dim txRole As String = TryCast(row.ItemArray(4), String)
Dim txPhone As String = TryCast(row.ItemArray(5), String)
Dim drpEmpl As String = TryCast(row.ItemArray(6), String)
Dim txVIP As String = TryCast(row.ItemArray(7), String)
Dim drpLCB As String = TryCast(row.ItemArray(8), String)
'Find the button
Dim button As Button = DirectCast(sender, Button)
'Find parent row
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
'find DropDownlist and textbox
Dim ddl As DropDownList = TryCast(parentRow.FindControl("txtLoginName"), DropDownList)
Dim txtNewUser As TextBox = TryCast(parentRow.FindControl("txtNewUser"), TextBox)
If txtNewUser IsNot Nothing AndAlso ddl IsNot Nothing Then
'add new listitem here
Dim customItem As New ListItem(txtNewUser.Text, txtNewUser.Text)
ddl.Items.Add(customItem)
End If
Dim ddlvalue As String = ""
Dim idx As Integer = grvStudentDetails.EditIndex
If drpEmpl = "Other" Then
ddlvalue = DirectCast(grvStudentDetails.FindControl("txtOther"), TextBox).Text
' Else
' ddlvalue = drpEmpl
End If
If txLName IsNot Nothing OrElse txLName IsNot Nothing OrElse txEmail IsNot Nothing OrElse txRole IsNot Nothing OrElse txPhone IsNot Nothing OrElse drpEmpl IsNot Nothing OrElse txVIP IsNot Nothing OrElse drpLCB IsNot Nothing Then
' Response.Write(String.Format("{0} {1} {2} {3} {4} {5} {6} {7} <br/>", txLName, txName, txEmail, txRole, txPhone, drpEmpl, txVIP, drpLCB))
'Try
Dim dateentered As String = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
'Response.Write(dateentered)
'Response.End()
Dim s As String
Dim count As Integer
'If LoginName already exists, alert user
s = "SELECT Count(*) FROM Employee_Roster WHERE login_id = " & txLName
'Response.Write(s)
'Response.End()
Dim connSt As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim connc As New OleDbConnection(connSt)
Dim cmdc As New OleDbCommand(s, connc)
'cmdc.Parameters.AddWithValue("login_id", txtLoginName.SelectedValue)
connc.Open()
' cmdc.ExecuteNonQuery()
count = cmdc.ExecuteScalar()
' Now let's see if we found existing record
If count > 0 Then
'Display some feedback to the user to let them know it was processed
lblResult.ForeColor = System.Drawing.Color.Green
lblResult.Text = "User already is in the Excel Sheet!"
Else
s = "INSERT INTO Employee_Roster(login_id, FullName, Email_Address, Role_Dept,Phone,Employer,VP,entryDate,Notes) VALUES "
s += "('" & txLName & "', '" & txName & "', '" & txEmail & "', '" & txRole & "', '" & txPhone & "', '" & ddlvalue & "','" & txVIP & "','" & dateentered & "', '" & drpLCB & "')"
Response.Write(s)
Response.End()
Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Display some feedback to the user to let them know it was processed
lblResult.ForeColor = System.Drawing.Color.Green
lblResult.Text = "Record successfully saved!"
'Clear the form
txLName = ""
txLName = ""
txEmail = ""
txRole = ""
txPhone = ""
txVIP = ""
End If
' Catch
'If the message failed at some point, let the user know
lblResult.ForeColor = System.Drawing.Color.Red
lblResult.Text = "Your record failed to save, please try again."
' End Try
End If
Next
End If
' Catch ex As Exception
'Throw New Exception(ex.Message)
' End Try
End Sub
Its very clear that your controls are residing inside your page and casting button.NamingContainer to GridViewRow is invalid.
The solution is that you don't need to use the FindControl if your controls have this property set runat="server". Just use the ID you give to them.
One more thing to point out is you need to use parametrized queries. Your queries are prone to SQL Injection . check How do I create a parameterized SQL query? Why Should I?
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
this button is out side of Gridview and this button belongs to ASP.addtoroster_aspx
but when you say button.NamingContainer it points ASP.addtoroster_aspx as it holds that
button,so casting is failing.

Creating Control Arrays in Vb 2010 with table column names not reading Rows

I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.

Exception Error must be type IListSource, IEnumerable or IDataSource. Gridview

I get a catch exp as Exception Error in which says, data source is an invalid type, it must either be of the type IListSource, IEnumerable or IDataSource.
This error comes when I try to add a new record to a database through a gridview, so I get the data from database nicely into this gridview, therefore I do not understand that I get a catch exp as exception when the database is not unavailable.
The #thesli_number OleDbType.VarChar Value = thenumber is type of number in the db.
'Add new record to DB
Protected Sub AddNewTask(ByVal sender As Object, ByVal e As EventArgs)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("txttestcat"), TextBox).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("txttestinfo"), TextBox).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("txttestnumber"), TextBox).Text
Dim strSQL As String = ""
strSQL = "" & _
"INSERT INTO [TableTest] " & _
"([test_cat], [test_info], [test_number])" & _
"VALUES (#thesli_cat, #thesli_info, #thesli_number)"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.VarChar).Value = thenumber
GridView1.DataSource = cmd
GridView1.DataBind()
'MsgBox("Row(s) Added !! ")
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
EDIT................EDIT.................EDIT...................EDIT
Ok i can now add data to the gridview, i can delete a record and i can add a new record.
But i cant get the update event to work, can u see whats wrong in this new code !?
'Update record
Protected Sub UpdateTask(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim theid = Convert.ToInt32(DirectCast(GridView1.FooterRow.FindControl("lbltestid"), Label).Text)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("lbltestcat"), Label).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("lbltestinfo"), Label).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("lbltestnumber"), Label).Text
Dim strSQL As String = ""
strSQL = "" & _
"UPDATE [TableTest] " & _
"SET [test_cat] = #thesli_cat, [test_info] = #thesli_info, [test_number] = #thesli_number " & _
"WHERE [test_id] = #thesli_id"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_id", OleDbType.Integer).Value = theid
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.Integer).Value = thenumber
cmd.ExecuteNonQuery()
'MsgBox("Row(s) Updated !! ")
GridView1.EditIndex = -1
GetRecords()
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
If the answer to your original question was answered in my comment above (posted below here in quotes), then you should mark this question as answered, then post an entirely new question so you get more accurate responses. This question no longer applies to your actual problem.
My answer which, in your comment, solved your original question:
That example (referring to the link in your comment above) does not directly assign an
OleDbCommand to the DataSource, because it
can't. If you look at the example the author passes the cmd variable
to the GetData function GetData(cmd), which more than likely executes
the stored procedure and returns a DataSource supported type (e.g.
IListSource, IEnumerable or IDataSource).

Conversion from string "DESC" to type 'Double' is not valid

I am developing a site in ASP.Net and VB.Net that will enable users to sort data in a GridView in Ascending or Descending order.
The records are coming from an SQL Server Express database.
I go to click on a column heading to sort the data and I get the following error:
'Conversion from string "DESC" to type 'Double' is not valid.'
Below is the code I am using for the sorting:
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim sqlConn As New SqlConnection
Dim sqlCmd As New SqlClient.SqlCommand
Dim sqlReader As SqlDataReader
'If no values are supplied in the textbox, throw an error message.
If TextBox2.Text = "" Then
MsgBox("A centre code needs to be provided...")
End If
If TextBox2.Text <> "" Then
'Telling the system the location of the database.
sqlConn.ConnectionString = "server=servername;Initial Catalog=dbName;Trusted_Connection=yes"
'Here we are opening the connection to the database.
sqlConn.Open()
'This is to say that sqlCmd is a stored procedure.
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure
'This is creating the command to execute the stored procedure based on the information given in the connection string.
sqlCmd = sqlConn.CreateCommand
'The command is triggered to execute the stored procedure which grabs all information for the specific centre.
sqlCmd.CommandText = "exec GetAllInformationKCSEBoxes '" & TextBox2.Text & "' "
'This will read the rows in the database.
sqlReader = sqlCmd.ExecuteReader()
GridView2.Columns.Clear() 'If there are rows of data that match are criteria
If (sqlReader.HasRows) Then
'The rows of data are grabbed for the specific centre from the database using the data reader.
GridView2.DataSource = sqlReader
GridView2.DataBind()
GridView2.Columns.Clear()
Else
MsgBox("The centre code provided does not exist...")
End If
'This is closing the connection to the database once we have finished with it.
sqlConn.Close()
'This is to clear the list of items out of the GridView box.
End If
End Sub
Property GridViewSortDirection() As String
Get
If IsNothing(ViewState.Item("GridViewSortDirection")) Then
Return "desc"
End If
Return ViewState.Item("GridViewSortDirection")
End Get
Set(ByVal Value As String)
ViewState.Item("GridViewSortDirection") = Value
End Set
End Property
Function GetSortDirection() As String
Dim GridViewSortDirectionNew As String
Select Case GridViewSortDirection
Case "DESC"
GridViewSortDirectionNew = "ASC"
Case "ASC"
GridViewSortDirectionNew = "DESC"
Case Else
GridViewSortDirectionNew = "DESC"
End Select
GridViewSortDirection = GridViewSortDirectionNew
Return GridViewSortDirectionNew
End Function
Protected Sub GridView_Sorting1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView2.Sorting
Dim myPageIndex As Integer = GridView2.PageIndex
Dim mySortdirection As String = GetSortDirection()
Dim sortExpression = e.SortExpression
Dim dv As New DataView()
If (GridViewSortDirection = SortDirection.Ascending) Then
GridViewSortDirection = SortDirection.Descending
'SortGridView(sortExpression, "DESCENDING")
Else
GridViewSortDirection = SortDirection.Ascending
End If
'dv.Table = GridView2.DataSource
' dv.Sort = e.SortExpression & " " & mySortdirection
' GridView2.DataSource = dv
'
' GridView2.DataBind()
'
' GridView2.PageIndex = myPageIndex
End Sub
'Protected Sub SortGridView(string sortExpression,string direction)
'DataTable dt = GetData().Tables[0]
' DataView(GridView2 = New DataView(GridView2))
' GridView2.Sort = sortExpression + Direction
'
' GridView1.DataSource = GridView2
' GridView1.DataBind()
'
' End Sub
I am not sure what this error means as I am not using a double, I am using a String.
My GridView is as follows:
<asp:GridView ID="GridView2" runat="server" Height="143px" AllowSorting="true" OnSorting="GridView_Sorting1"
How can I get over this problem?
All help and advice will be greatly appreciated.
Many Thanks,
Dan
You use the comparison GridViewSortDirection = SortDirection.Ascending in your code which looks like it may be the cause of the problem. You are trying to compare a string with an enum which is going to cause you conversion issues. You may want to change all those string declarations to use the enum so that you are comparing like with like.
This is certainyl likely to be a problem in your code and possibly the problem. :)

Resources