Failed to convert parameter value from a List`1 to a String - vb.net

I am getting the error message:
"Failed to convert parameter value from a List`1 to a String"
and I am not sure how to correct the issue. It happens when I attempt to save a cleaningList to a Cleaner object in a database.
I am very new to visual basic and appreciate any feedback to help make this program work.
Public Class FrmMain
Dim currentRoom As String
Dim lastId As Integer
Dim cleaners As New BindingList(Of Cleaner)
'new instance of cleaner and storing it in a reference variable
Dim currentCleaner As New Cleaner()
'-------------Functions----------------
Private Function connectWithDb() As SqlConnection
'create a connection string
Dim connectionString As String = "Server=(LocalDB)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=C:\Users\Julia\Desktop\JklimeckFinalProject\JklimeckFinalProject\cleanerLists.mdf;"
'create connection object and tell it how to connect using connectionString
Dim dbConnection As New SqlConnection(connectionString)
'open the connection
dbConnection.Open()
'return the connection
Return dbConnection
End Function
'function to change the list to a string seperated by commas
Public Function changeToString() As String
'turn the list of strings into a single string for the database
'trim the leading white space so it won't show up when the list is
'converted back later
currentCleaner.CleaningList = LTrim(String.Join(",", currentCleaner.ItemList.ToArray()))
Return currentCleaner.CleaningList
End Function
'public function to get index of items that are selected
Public Function GetAllItems(index As Integer) As CheckState
End Function
'function to generate a cleaning list
Public Function getCleanList() As List(Of String)
'if statement to display tasks in lbxTasks
Dim indexChecked As Integer
'variable to hold the tasks that are listed depending on the room
'selected ' for current cleaner
Dim itemList As New List(Of String)
'determine the room and create the list of tasks depending on the checked boxes
If currentRoom = "Living Room" Then
itemList.AddRange(currentCleaner.LivRoomTasks)
ElseIf currentRoom = "Kitchen" Then
itemList.AddRange(currentCleaner.KitchenTasks)
ElseIf currentRoom = "Bathroom" Then
itemList.AddRange(currentCleaner.BathroomTasks)
ElseIf currentRoom = "Bedroom" Then
itemList.AddRange(currentCleaner.BedroomTasks)
ElseIf currentRoom = "Dining Room" Then
itemList.AddRange(currentCleaner.DinRoomTasks)
ElseIf currentRoom = "Office" Then
itemList.AddRange(currentCleaner.OfficeTasks)
ElseIf currentRoom = "Laundry Room" Then
itemList.AddRange(currentCleaner.LauRoomTasks)
ElseIf currentRoom = "General" Then
itemList.AddRange(currentCleaner.GeneralTasks)
End If
For Each indexChecked In cbxRoomItems.CheckedIndices
lbxTasks.Items.Add(itemList.Item(indexChecked).ToString)
Next
Return itemList
End Function
'function to seperated the string version of the list
Public Function changeToList() As List(Of String)
'change the comma separated sting back to a list by spliting it at the commas
lbxTasks.Items.AddRange(currentCleaner.CleaningList.Split(New Char() {","c}))
Return currentCleaner.ItemList
End Function
Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'when the application loads, show list of cleaners and display by name
lbxNames.DataSource = cleaners
lbxNames.DisplayMember = "Name"
Dim dbConnection As SqlConnection = connectWithDb()
'string of sql
Dim sqlString As String = "SELECT * FROM Cleaner"
'command object pass in what to run and the object
Dim selectCommand As New SqlCommand(sqlString, dbConnection)
'place in a try catch block to keep exceptions from crashing application
Try
'variable to hold the sqlDataReader object
Dim reader As SqlDataReader = selectCommand.ExecuteReader()
If reader.HasRows Then
'read is boolean
While reader.Read
'call the sub
populateCleaners(reader)
End While
End If
reader.Close()
'determine the highest ID number in the database
'and store it in a class level variable so we can access it
'where ever it is needed
Dim identSql As String = "SELECT IDENT_CURRENT('Cleaner') as lastID"
Dim identCom As New SqlCommand(identSql, dbConnection)
Dim identReader As SqlDataReader = identCom.ExecuteReader
If identReader.HasRows Then
identReader.Read()
lastId = CInt(identReader.Item("lastId"))
End If
Catch ex As Exception
End Try
'close and dispose the connection to the db
dbConnection.Close()
dbConnection.Dispose()
End Sub
'Sub to populate the database with a new character
Private Sub populateCleaners(reader As SqlDataReader)
Dim dbCleaner As New Cleaner()
changeToString()
'get info from reader and store into new object
dbCleaner.Id = CInt(reader.Item("Id"))
dbCleaner.Name = reader.Item("Name").ToString
dbCleaner.CleaningList = reader.Item("CleaningList").ToString
'add to binding list
cleaners.Add(dbCleaner)
End Sub
'----------------Butttons------------------
'add to list button
Private Sub btnClean_Click(sender As Object, e As EventArgs) Handles btnClean.Click
'label to show the correct list is being displayed
lblCurrentCleaner.Text = currentCleaner.Name
getCleanList()
End Sub
'save cleaning list
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim newCleaner As New Cleaner()
'referencing object and assigning it to the Name property for the new cleaner
newCleaner.Name = txtName.Text
'exception if the user does not enter a name
Try
newCleaner.Name = txtName.Text
Catch ex As Exception
MessageBox.Show("a cleaner has no name")
End Try
For ctr = 0 To lbxTasks.Items.Count - 1
newCleaner.ItemList.Add(lbxTasks.Items(ctr).ToString)
'change this list to a string
changeToString()
Next
newCleaner.CleaningList = changeToString()
lbxTasks.Items.Clear()
cleaners.Add(newCleaner)
currentCleaner = newCleaner
'update a cleaning list if the Id is already in the database, or create a new object
Dim dbConnection As SqlConnection = connectWithDb()
Dim sqlString As String
If currentCleaner.Id > 0 Then
sqlString = "UPDATE Cleaner SET Name = #name, CleaningList = #cleaningList WHERE Id = #id"
Else
sqlString = "INSERT INTO Cleaner (Name, CleaningList) VALUES(#name, #cleaningList)"
'increment the last Id and save that id number to the new entry in the db
lastId += 1
currentCleaner.Id = lastId
End If
Dim com As New SqlCommand(sqlString, dbConnection)
'set the values of current cleaner in the database
com.Parameters.Add("#id", SqlDbType.Int).Value = currentCleaner.Id
com.Parameters.Add("#name", SqlDbType.VarChar).Value = currentCleaner.Name
com.Parameters.Add("#cleaningList", SqlDbType.NVarChar).Value = currentCleaner.ItemList
Try
Dim result = com.ExecuteNonQuery()
MessageBox.Show(result.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I have a Cleaner class that stores the public properties.
In the program the user clicks on different buttons that populate a checklistbox with different items found in that room, by selecting the items and clicking btnClean it populates a listbox with a list of tasks associated with the items the user selected. My problem seems to be centered around that list; it is stored in a list(of String), but I made a function to turn that list into a single string separated by commas so it can be stored in a database and another function to separated that list so it can be displayed back in the listbox when the user's name is selected.
I am not sure where it is I am going wrong.
The exception is being thrown in:
'save cleaning list
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim newCleaner As New Cleaner()
'referencing object and assigning it to the Name property for the new cleaner
newCleaner.Name = txtName.Text
'exception if the user does not enter a name
Try
newCleaner.Name = txtName.Text
Catch ex As Exception
MessageBox.Show("a cleaner has no name")
End Try
For ctr = 0 To lbxTasks.Items.Count - 1
newCleaner.ItemList.Add(lbxTasks.Items(ctr).ToString)
'change this list to a string
changeToString()
Next
lbxTasks.Items.Clear()
cleaners.Add(newCleaner)
currentCleaner = newCleaner
'update a cleaning list if the Id is already in the database, or create a new object
Dim dbConnection As SqlConnection = connectWithDb()
Dim sqlString As String
If currentCleaner.Id > 0 Then
sqlString = "UPDATE Cleaner SET Name = #name, CleaningList = #cleaningList WHERE Id = #id"
Else
sqlString = "INSERT INTO Cleaner (Name, CleaningList) VALUES(#name, #cleaningList)"
'increment the last Id and save that id number to the new entry in the db
lastId += 1
currentCleaner.Id = lastId
End If
Dim com As New SqlCommand(sqlString, dbConnection)
com.Parameters.Add("#name", SqlDbType.VarChar).Value = currentCleaner.Name
com.Parameters.Add("#cleaningList", SqlDbType.NVarChar).Value = currentCleaner.ItemList
Try
Dim result = com.ExecuteNonQuery()
MessageBox.Show(result.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Again thank you for any suggestions/help!

Related

Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

I have the following requirement,
I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.
(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.
(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.
Am I missing something here or is it like that? Any advice will be highly appreciated.
Im filling it in runtime using a procedure.
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
cmbDisProfile.DataSource = tempTb
cmbDisProfile.DisplayMember = "discount_profile"
End Sub
Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.
My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.
Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)
Return fetchedDataTable
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)
Dim SqlCmd As New SqlCommand(sqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
dataAdapter.Update(tbToUpdate)
End Sub
Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
Try
Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"
'Dim searchString As String = txtCategoryCode.Text
' searchOwnerCmd.Parameters.Clear()
' searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(searchSql)
If tempTb.Rows.Count = 0 Then
Return False
Else
Return True
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)
Return fetchedSearchTB
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].
How do you fill/populate your ComboBox with Data From Database Table ?
In this link, Microsoft docs state, that:
Use the SelectedIndex property to programmatically determine the index
of the item selected by the user from the DropDownList control. The
index can then be used to retrieve the selected item from the Items
collection of the control.
In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.
proposed,
ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"
does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
Dim i As Integer = 0
For i = 0 To tempTb.Rows.Count - 1
cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
Next
End Sub
After adding we can use the following code to display the data on combobox (DropDownList).
Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
Try
Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
If Len(txtItCode.Text) < 4 Then
cmdAdd.Enabled = False
cmdDelete.Enabled = False
cmdSave.Enabled = False
Else
If tempTb.Rows.Count > 0 Then
With tempTb
txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
End With
cmdAdd.Enabled = False
cmdDelete.Enabled = True
cmdSave.Enabled = True
Else
cmdAdd.Enabled = True
cmdDelete.Enabled = False
cmdSave.Enabled = False
txtItName.Text = ""
Call fillItCategories()
Call fillProProfile()
Call filldisProfiles()
Call fillFinCat()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

Converting Combobox Value.Member from Sttring to Integer?

I have 2 comboboxes which contain ID columns (SID & CID) as the valuemember and the displayMember is text.
I want to use the valueMembers to INSERT into an SQL database.
However the ValueMember property is a String and the column in the database is an Integer.
How can I get these 2 valueMembers converted into Integers.
The code for the complete form is shown below.
Imports System.Data.SqlClient
Imports My_Greeting.Add_VersesDataSetTableAdapters
Public Class frmAddRecord
Private MyDatAdp As New SqlDataAdapter
Private MyDataTbl As New DataTable
Private sql As String = Nothing
Private ds As New DataSet()
Private stepinfo As String = String.Empty
Dim E1 As String
Dim E2 As String
Dim Verse As String
Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
Private Sub frmAddRecord_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TopMost = True
Me.WindowState = FormWindowState.Normal
Me.Sub_EventTableAdapter1.Fill(Me.EventSubDataSet1.Sub_Event)
Me.Event_TypeTableAdapter1.Fill(Me.PrimEventDataSet1.Event_Type)
Dim evt As String
Dim SEvt As String
Dim Verse As String
Dim sql As String = Nothing
Dim ds As New DataSet()
Dim stepinfo As String = String.Empty
Try
stepinfo = "Step: instatiate connection"
Using connection As New SqlConnection(connectionString)
stepinfo = "step: test open connection"
connection.Open()
sql = "Select SID, EVENT from Event_Type"
Using adaptor As New SqlDataAdapter(sql, connection)
adaptor.Fill(ds, "Tab_Event_Type")
End Using
stepinfo = "Load second data"
sql = "Select BID,SUBEVENT from Sub_Event"
Using adaptor As New SqlDataAdapter(sql, connection)
adaptor.Fill(ds, "Tab_Sub_Event")
End Using
End Using
stepinfo = "Step: Bind Event combobox"
cboEvent.DataSource = ds.Tables("Tab_Event_Type")
cboEvent.ValueMember = "SID"
cboEvent.DisplayMember = "Event"
stepinfo = "Bind Sub_Event combobox"
cboSEvent.DataSource = ds.Tables("Tab_Sub_Event")
cboSEvent.ValueMember = "BID"
cboSEvent.DisplayMember = "SubEvent"
Catch ex As Exception
MessageBox.Show($"Error:{stepinfo}{vbNewLine}{ex.ToString}")
End Try
evt = cboEvent.ValueMember
SEvt = cboSEvent.ValueMember
Verse = txtNewVerse.Text
E1 = CType(evt, Integer)
E2 = CType(SEvt, Integer)
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim query As String = String.Empty
query &= "INSERT INTO Verse (Event, Event_Sub, Verse)"
query &= "VALUES (#Event, #Event_Sub, #Verse)"
Using conn As New SqlConnection("Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True")
Using Comm As New SqlCommand()
With Comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#Event", E1)
.Parameters.AddWithValue("#Event_Sub", E2)
.Parameters.AddWithValue("#Verse", Verse)
End With
Try
conn.Open()
Comm.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End Using
End Sub
End Class
I have tried CInt and CType, but they dont work.
Conversion from string "SID" to type 'Integer' is not valid.
The issue lies in these lines of code:
cboEvent.ValueMember = "SID"
...
Dim evt As String
...
evt = cboEvent.ValueMember
...
Dim E1 As String
...
E1 = CType(evt, Integer)
You can simplify it into
Dim E1 As String = CType("SID", Integer)
Which is obviously not going to work. I'm not sure of your intent, but this is surely your issue.
Edit to address your comments
Here is the title of your question Converting Combobox Value.Member from Sttring [sic] to Integer?
Let's try to figure out what you are trying to do. (By the way, it is nice when we don't need to try to figure out a questioner's intent; rather it is apparent. Anyway, let's do that now)
Regarding this nugget: Combobox Value.Member, it's unclear whether you actually want the ValueMember, SelectedValue, or Text (Text being the closest proxy to Value alone).
The ValueMember tells a control which property to return via SelectedValue when the control is data-bound. For example,
Dim source = (
From i In Enumerable.Range(5, 5)
Select New With {
.Number = i,
.Square = i ^ 2
}).ToList()
ComboBox1.DataSource = source
ComboBox2.DataSource = source
ComboBox2.DisplayMember = "Number"
ComboBox2.ValueMember = "Square"
Let's see what the results of the three properties in question are, for both ComboBoxes
MessageBox.Show($"{ComboBox1.ValueMember}, {ComboBox2.ValueMember}")
, Square
MessageBox.Show($"{ComboBox1.Text}, {ComboBox2.Text}")
{ Number = 5, Square = 25}, 5
MessageBox.Show($"{ComboBox1.SelectedValue}, {ComboBox2.SelectedValue}")
{ Number = 5, Square = 25}, 25
The last one is probably what you want. ComboBox2.ValueMember has been set as the "Square" property of the anonymous type in the LINQ expression.
So in your example, the offending code is in my first code block, and it should be obvious that assigning evt = cboEvent.ValueMember is wrong and that you probably wanted the SelectedValue
evt = cboEvent.SelectedValue
which should have been clear from our comments, and answer. #jmcilhinney's comment specifically
The ValueMember is the name of the member from which the values come. It is NOT the value(s). That's what the SelectedValue property is for. The SelectedValue is where you'll find the value from the specified member of the SelectedItem. – jmcilhinney 16 hours ago
that last part again
16 hours ago
You can lead a horse to water, but you can't make him drink.

Defining Variables that are accessible page wide

Good morning guys,
I am working on vb.net. The aim is to make a CodeFile run some sql queries and then return the values to the webpage as an sqldatasource query parameter on page load.
I have the following vb code
Partial Class Consult
Inherits Page
Public totalCount As Integer = "0"
'*******Here i declare the variable***************
Public Property PatNo() As String
Get
Return ViewState("PatNo")
End Get
Set(ByVal value As String)
ViewState("PatNo") = value
End Set
End Property
Public PatNam As String = "abc"
Public ConID As String = "abc"
Public TreatType As String = "abc"
Public HPC As Char = "abc"
Public LvTyp As RadioButtonList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.PatNo = Request.QueryString("pNo")
Session("PatientNo") = PatNo
Dim ConsultationID As String = Request.QueryString("consultID")
ConID = ConsultationID
Response.Write(PatNo)
Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Using con As New SqlConnection(constr)
'**********BELOW LINE CAUSES ERROR**************
Dim query As String = "SELECT * FROM hPatients WHERE pNO=#PatNo"
query += "SELECT * FROM hPatients WHERE pNO='001/000034824'"
Using cmd As New SqlCommand(query)
cmd.Parameters.Add("#PatNo", SqlDbType.NVarChar).Value = PatNo
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds)
gvPatientInfo.DataSource = ds.Tables(0)
'Return ds.Tables(0).Rows(0).Item(2)
'Response.Write(ds.Tables(0).Rows(0).Item(2))
gvPatientInfo.DataBind()
gvClientInfo.DataSource = ds.Tables(1)
gvClientInfo.DataBind()
End Using
End Using
End Using
End Using
If Not Me.IsPostBack Then
'Dim di As DataInfo = Me.GetInfo()
'Populating a DataTable from database.
Dim dt As DataTable = Me.GetData()
'Response.Write(ConID + " " + PatNo)
'Building an HTML string.
Dim html As New StringBuilder()
'Table start.
html.Append("<table border = '1' class = 'table'>")
'Building the Header row.
html.Append("<tr>")
For Each column As DataColumn In dt.Columns
html.Append("<th>")
html.Append(column.ColumnName)
html.Append("</th>")
Next
html.Append("</tr>")
'Building the Data rows.
For Each row As DataRow In dt.Rows
html.Append("<tr>")
For Each column As DataColumn In dt.Columns
html.Append("<td>")
html.Append(row(column.ColumnName))
html.Append("</td>")
Next
html.Append("</tr>")
Next
'Table end.
html.Append("</table>")
'Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(New Literal() With { _
.Text = html.ToString() _
})
End If
End Sub
The error i get is
Must declare the scalar variable "#PatNo".
The error occurs in the first step of getting the variable to execute the query in the page_load function.
The second step would be to get the result of the query and use on the webpage.
Somebody, Anybody, Please HELP!!!.
I think the problem is with this line:
cmd.Parameters.Add("PatNo", SqlDbType.NVarChar).Value = PatNo
Change the name from "PatNo" to "#PatNo" and it should work.

Deleting multiple records from sql bound Datagrid

The procedures below allowed me to delete several records at once by checking the checkbox on my datagrid. The procedure was written on ASP.net but now I am using a winform on VB.net.
I have a datagrid with column name "Delete" where the checkboxes are located. The user would check
the records it wants to delete and the would delete those records. I use the "Ticket Number" column values as the parameter for my query.
The issue I have is that since was written for ASP.Net, I cannot find how the winform VB.net equivalent for this line:
Dim chkDelete As CheckBox = DirectCast(grdRoster.Rows(i).Cells(0).FindControl("Delete_Row"), CheckBox)
FindControl is not a member of System.Windows.Forms.DataGridViewCell. Plus I am pretty sure that the whole line is wrong since the checkboxes
are located on a datagrid column set as ColumnType: DataGridViewCheckBoxColumn and are not really individual controls.
How can I get the same result on a winform? Here is my entire code.
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
'Create String Collection to store
'IDs of records to be deleted
Dim ticketNumberCollection As New StringCollection()
Dim strTicketNumber As String = String.Empty
'Loop through GridView rows to find checked rows
For i As Integer = 0 To grdRoster.Rows.Count - 1
Dim chkDelete As CheckBox = DirectCast(grdRoster.Rows(i).Cells(0).FindControl("Delete_Row"), CheckBox)
If chkDelete IsNot Nothing Then
If chkDelete.Checked Then
strTicketNumber = grdRoster.Rows(i).Cells(1).ToString
ticketNumberCollection.Add(strTicketNumber)
End If
End If
Next
'Call the method to Delete records
DeleteMultipleRecords(ticketNumberCollection)
' rebind the GridView
grdRoster.DataBind()
End Sub
' Sub to delete multiple records
' #param "idCollection" calls the string collection above
' and deletes the selected record separated by ","
Private Sub DeleteMultipleRecords(ByVal ticketNumberCollection As StringCollection)
Dim IDs As String = ""
'Create string builder to store
'delete commands separated by ,
For Each id As String In ticketNumberCollection
IDs += id.ToString() & ","
Next
Try
Dim strTicketID As String = IDs.Substring(0, IDs.LastIndexOf(","))
DataSheetTableAdapter.DeleteRecord(strTicketID)
Catch ex As Exception
Dim errorMsg As String = "Error in Deletion"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
Me.Close()
End Try
End Sub
for deleting multiple records from a data bound gridview you should create the DataGridViewCheckBoxColumn at run time
Dim chk As New DataGridViewCheckBoxColumn()
DataGridView1.Columns.Add(chk)
chk.HeaderText = "Select"
'then bind your datagridview with dataset
Dim sql As String = "SELECT * FROM table_name"
' Dim connection As New SqlConnection(connectionString)
conn.Open()
sCommand = New SqlCommand(sql, conn)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "table_name")
sTable = sDs.Tables("table_name")
DataGridView1.DataSource = sDs.Tables("table_name")
'then traverse through each column and get the checked values
Try
DataGridView1.EndEdit()
For j = Me.DataGridView1.Rows.Count - 1 To 0 Step -1
If Not IsDBNull(DataGridView1.Rows(j).Cells(0).Value) Then
If DataGridView1.Rows(j).Cells(0).Value = True Then
check = True
If MessageBox.Show("Do you want to delete these records?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
For i = Me.DataGridView1.Rows.Count - 1 To 0 Step -1
If Not IsDBNull(DataGridView1.Rows(i).Cells(0).Value) Then
If DataGridView1.Rows(i).Cells(0).Value = True Then
'remove the checked columns and update datatable
DataGridView1.Rows.RemoveAt(i)
sAdapter.Update(sTable)
End If
End If
Next
Else
Return
End If
Else
End If
End If
Next
If check = False Then
MsgBox("Nothing Selected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try

query database with each object in Arraylist and databind to gridview?

I have a function that returns a list of account numbers as an Arraylist. I am trying to use each account as a command parameter in another sub routine to get more data about each account number. This only returns the data for the last account number in the arraylist. I need to use each account number, call the database, get the additional information and store ALL of the data into a Gridview (databind). Example: If I had 3 account numbers in my arraylist return 3 rows of data to the gridview. I am struggling with how to get ALL of the information for each value (account number) in the Arraylist. Can someone point me in the right direction?? I think this can be done but I am not certain if my approach is correct or not. Perhaps I need to create datatables that contain the additional information for each value passed via the arraylist....Any Ideas??
#jwatts1980 thanks for the comment: I will try to clarify. I have an arraylist of account numbers (and maybe this is where I am off track) I am trying to use the values in this ArrayList as command parameters in another call to a different table/file that returns more info on those accounts. I will provide a portion of the code to help clarify what it is I am attempting to do:
Private Function ReturnMultAccts(ByVal strAcct) As ArrayList
Dim acctsDetail As New ArrayList
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT DISTINCT * FROM FILE WHERE ACCTNUM=?"
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("ACCTNUM", OdbcType.VarChar, 20).Value = strAcct
Dim rdrUsers As OdbcDataReader = cmd.ExecuteReader()
If rdrUsers.HasRows Then
While rdrUsers.Read()
acctsDetail.Add(Trim(rdrUsers.Item("ACCTNUM")))
End While
End If
rdrUsers.Close()
conn.Close()
End Using
End Using
This returns an Arraylist of Account Numbers (Lets say it is 3 acct numbers). I call this Function from another Sub:
Private Sub GetMoreAcctInfo(ByVal strAcct)
'Create New ArrayList
Dim MultAccts As New ArrayList
'Pass strAcct to Function to get Multiples
MultAccts = ReturnMultAccts(strAcct)
'Create the variable BachNum for the loop
Dim BachNum As String = MultAccts.Item(0)
For Each BachNum In MultAccts
'Get All of the necessary info from OtherFile based on the BachNum for BOS's
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, OTHACCTNUM FROM OtherFile WHERE OTHACCTNUM=?" 'Equal to the items in the arraylist
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("OTHACCTNUM", OdbcType.VarChar, 20).Value = BachNum
Using adapter = New OdbcDataAdapter(cmd)
Dim DS As New DataSet()
adapter.Fill(DS)
GridView1.DataSource = DS
GridView1.DataBind()
End Using
End Using
End Using
Next
End Sub
Hopefully this clarifies what I am attempting to do...??
To elaborate on my suggestion, you will need a list of strongly typed objects. You can add those items to the list, then bind the list to the GridView.
I'll start at the beginning. You know what kind of data is coming from your database: ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, and OTHACCTNUM. So you can use those to create an object.
Friend Class AccountClass
Private pACCTNUM As string = ""
Private pBILSALCOD1 As string = ""
Private pBILSALCOD2 As string = ""
Private pBILSALCOD3 As string = ""
Private pOTHACCTNUM As string = ""
Public Property ACCTNUM() As string
Get
Return pACCTNUM
End Get
Set(ByVal value as string)
Me.pACCTNUM = value
End Set
End Property
Public Property BILSALCOD1() As string
Get
Return pBILSALCOD1
End Get
Set(ByVal value as string)
Me.pBILSALCOD1 = value
End Set
End Property
Public Property BILSALCOD2() As string
Get
Return pBILSALCOD2
End Get
Set(ByVal value as string)
Me.pBILSALCOD2 = value
End Set
End Property
Public Property BILSALCOD3() As string
Get
Return pBILSALCOD3
End Get
Set(ByVal value as string)
Me.pBILSALCOD3 = value
End Set
End Property
Public Property OTHACCTNUM() As string
Get
Return pOTHACCTNUM
End Get
Set(ByVal value as string)
Me.pOTHACCTNUM = value
End Set
End Property
Sub New(ByVal ACCTNUM As string, ByVal BILSALCOD1 As string, ByVal BILSALCOD2 As string, ByVal BILSALCOD3 As string, ByVal OTHACCTNUM As string)
Me.ACCTNUM = ACCTNUM
Me.BILSALCOD1 = BILSALCOD1
Me.BILSALCOD2 = BILSALCOD2
Me.BILSALCOD3 = BILSALCOD3
Me.OTHACCTNUM = OTHACCTNUM
End Sub
End Class
Then you rework the GetMoreAcctInfo() routine to use it.
Private Sub GetMoreAcctInfo(ByVal strAcct)
'Create New ArrayList
Dim MultAccts As ArrayList
'Pass strAcct to Function to get Multiples
MultAccts = ReturnMultAccts(strAcct)
'Create the variable BachNum for the loop
Dim BachNum As String
'Create the list to bind to the grid
Dim AcctInfo As New Generic.List(Of AccountClass)
'create the dataset
Dim DS As DataSet
For Each BachNum In MultAccts
'Get All of the necessary info from OtherFile based on the BachNum for BOS's
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, OTHACCTNUM FROM OtherFile WHERE OTHACCTNUM=?" 'Equal to the items in the arraylist
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("OTHACCTNUM", OdbcType.VarChar, 20).Value = BachNum
Using adapter = New OdbcDataAdapter(cmd)
DS = New DataSet()
adapter.Fill(DS)
For Each t As DataTable In DS.Tables
For Each r As DataRow In t.Rows
AcctInfo.Add(new AccountClass(r("ACCTNUM"), r("BILSALCOD1"), r("BILSALCOD2"), r("BILSALCOD3"), r("OTHACCTNUM")))
Next
Next
End Using
End Using
End Using
Next
GridView1.DataSource = AcctInfo
GridView1.DataBind()
End Sub