FlowLayoutPanel Update & Delete Records in Database - vb.net

Can someone tell me how i can manage Delete Record & Update Record from FlowLayoutPanel
So i have 1 user control :
then fetch the db:
Public Function FindTasksUser() As DataTable
Using cons As New SQLiteConnection(ServerStatus)
Using cmd As New SQLiteCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM Tasks WHERE accountName = #GetUser ORDER BY [ID] ASC;"
cmd.Parameters.AddWithValue("#GetUser", UserUserAcc).ToString()
cons.Open()
Using sda As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
then call the function in maincp form
Private Sub GenerateTasksUser()
FlowLayoutPanel3.Controls.Clear()
Dim dt As DataTable = New ClassBLL().GetTasksUser()
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As UserTasks() = New UserTasks(dt.Rows.Count - 1) {}
For i As Integer = 0 To 1 - 1
For Each row As DataRow In dt.Rows
Dim listItem As New UserTasks()
listItems(i) = listItem
listItems(i).TaskTitle = row("taskstitle").ToString()
listItems(i).TaskSubject = row("tasksubject").ToString()
listItems(i).TaskFrom = row("taskfromname").ToString()
FlowLayoutPanel3.Controls.Add(listItems(i))
Next
Next
End If
End If
End Sub
I have try inside user control img button this options, seems to delete the row, but im not sure is it the right one and how to delete from database
Private Sub Guna2ImageButton1_Click(sender As Object, e As EventArgs) Handles Guna2ImageButton1.Click
MainCP.FlowLayoutPanel3.Controls.RemoveByKey(Me.Name)
'or Directly to use Dispose
Dispose()
'or another option
Parent.Controls.Remove(Me)
'or another option i think is:
For Each control As Control In MainCP.FlowLayoutPanel3.Controls
MainCP.FlowLayoutPanel3.Controls.Remove(control)
control.Dispose()
Next
End Sub
And how to update in database when i click Checbox1 and button 2 to save the records in database in column "Status" with text "Done"

Most of the verbage to go with this code is provided in my comments. This has not been tested. Sqlite is an anethma to me. I gasp at the "flexable" typing.
The actual update code takes a list of the IDs from the original DataTable. You add the parameter once to the parameters collection and then loop through the values to update.
Public Class ClassBLL
Private ServerStatus As String = "Your connection string"
Public Sub UpdateRecords(lst As List(Of Integer))
Dim sql = "Update Tasks Set Status = 'Done' Where ID = #ID"
Using cn As New SQLiteConnection(ServerStatus),
cmd As New SQLiteCommand(sql, cn)
cmd.Parameters.Add("#ID", DbType.Int32)
cn.Open()
For Each i In lst
cmd.Parameters("#ID").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Public Function FindTasksUser(UserUserAcc As String) As DataTable
Dim dt As New DataTable()
Dim sql = "SELECT * FROM Tasks WHERE accountName = #GetUser ORDER BY [ID] ASC;"
Using cons As New SQLiteConnection(ServerStatus)
Using cmd As New SQLiteCommand(sql, cons)
cmd.Parameters.AddWithValue("#GetUser", UserUserAcc)
cons.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
End Using
Return dt
End Function
End Class
Private Class MainCP
Private UserAccount As String
Private Sub GenerateTasksUser()
FlowLayoutPanel3.Controls.Clear()
Dim dt As DataTable = New ClassBLL().FindTasksUser(UserAccount)
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As New List(Of UserTasks)
For Each row As DataRow In dt.Rows
Dim listItem As New UserTasks()
listItem.TaskTitle = row("taskstitle").ToString()
listItem.TaskSubject = row("tasksubject").ToString()
listItem.TaskFrom = row("taskfromname").ToString()
listItems.Add(listItem)
Next
FlowLayoutPanel3.Controls.AddRange(listItems.ToArray)
End If
End If
Dim IDList = (From row As DataRow In dt.AsEnumerable
Select CInt(row("ID"))).ToList
SomeOtherForm.ListOfIDs = IDList
End Sub
End Class
Public Class SomeOtherForm
Public Shared ListOfIDs As List(Of Integer)
Private Sub Guna2ImageButton1_Click(sender As Object, e As EventArgs) Handles Guna2ImageButton1.Click
'I don't think Me is referring to what you think it is.
For Each control As Control In MainCP.FlowLayoutPanel3.Controls
MainCP.FlowLayoutPanel3.Controls.Remove(control)
control.Dispose()
'You also need to get rid of any handlers you have added.
Next
Dim bll As New ClassBLL
bll.UpdateRecords(ListOfIDs)
End Sub
End Class
Public Class UserTasks
Inherits UserControl
Public Property TaskTitle As String
Public Property TaskSubject As String
Public Property TaskFrom As String
End Class

Related

Having issues when 2 users are working with the same program

Public Class DataAccess
Dim dataAcc As New DataAccess
Public Shared dtx As New DataTable
Private Shared ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Shared Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
I use that part to create the connection just like the example #Mary posted. Then:
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim numTicket As String = txtNoTicket.Text
Dim dtx As New DataTable
Dim pk As String
pk = txtNoTicket.Text
Dim con2 As New SqlConnection
Dim cmd2 As New SqlCommand
Dim dr As SqlDataReader
Dim dtx2 As DataTable
Dim status As Boolean = False
'If Not Integer.TryParse(ticket.Text, pk) Then
If String.IsNullOrEmpty(pk) Then
'ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "showDisplay();", True)
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
dtx = DataAccess.AddOneRecord(pk)
So when adding tickets the issue is the ticket 1 user adds, gets added to the other user even though they use different sessions and different computers. The program is in test fase right now.
You can get rid of Shared in the DatAccess class. Then each instance of the class will have its own data. Now you must declare an instance of the class and call the method on that instance.
Public Class DataAccess
Dim dataAcc As New DataAccess
Public dtx As New DataTable
Private ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim dtx As New DataTable
Dim pk = txtNoTicket.Text
If String.IsNullOrEmpty(pk) Then
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
Dim datAcc As New DataAccess
dtx = datAcc.AddOneRecord(pk)
End If
End Sub

Visual Basic display all output from query in multiple labels using FOR...NEXT Loop

Currently, my code is like this:
Private Sub btnAlaCarte_Click(sender As Object, e As EventArgs) Handles btnAlaCarte.Click
Dim item(2) As String
Dim description(2) As String
Dim price(2) As String
conn.Open()
sql = "SELECT name, description, price FROM Food WHERE id LIKE 'F%';"
cmd = New SqlCommand(sql, conn)
dr = cmd.ExecuteReader
If dr.HasRows Then
For count = 1 To 3 Step 1
dr.Read()
lklblItem1.Text = dr.GetValue(dr.GetOrdinal("name"))
lblDescription.Text = dr.GetValue(dr.GetOrdinal("description"))
lblPrice.Text = dr.GetValue(dr.GetOrdinal("price"))
Next
End If
dr.Close()
conn.Close()
End Sub
I have 3 set of label in my design. Each of the set consist of 1 linklabelItem, 1 labelDescription and 1 labelPrice. All of them will display different output from database. I manage to extract all of the data that i want. But now the problem is the FOR....NEXT loop only display the output at the first set.
Is there any possibility for me to use For....NEXT Loop to achieve my concept?
Hopes my question is clear enough.
In your case DataGridView control will do the job without explicit For .. Next loop.
' Create a class to represent a food item
Public Class AlaCarteItem
Public Property Name As String
Public Property Description As String
Public Property Price As Decimal
End Class
' Extract loading data into dedicated function with properly disposed sql connection
Private Function GetAlaCarte() As List(Of AlaCarteItem)
Dim query As String = "SELECT name, description, price FROM Food WHERE id LIKE 'F%';"
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(query, connection)
connection.Open()
Dim items = new List(Of AlaCarteItem)()
Using reader AS SqlDataReader = command.ExecuteReader()
While reader.Read()
Dim item As New AlaCarteItem With
{
.Name = reader.GetString(0),
.Description = reader.GetString(1),
.Price = reader.GetDecimal(2),
}
items.Add(item)
End While
End Using
Return items
End Using
End Using
End Function
Add DataGridView control to the form
Private btnAlaCarte_Click(sender As Object, e As EventArgs) Handles btnAlaCarte.Click
Me.DataGridView.DataSource = GetAlaCarte()
' Make all columns read only
For Each column As DataGridViewColumn in Me.DataGridView.Columns
column.ReadOnly = True
End With
End Sub
You can create DataGridView with predefined columns and make them readonly in design time, then you don't need to do this in the code.
Start in the form designer.
In the toolbox drag a BindingNavigator to the form. Reference https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/bindingnavigator-control-overview-windows-forms
Remove the buttons that you will not use by right clicking on the buttons and selecting delete. You will end up with a strip that looks like this.
Then, in the code
Fill a DataTable
Create a BindingSource
Set the DataSource of the BindingSource to the DataTable
Finally set the BindingSource property of the BindingNavigator control to the the BindingSource.
Next your will add DataBindings to each of your controls.
The .Add method takes 3 parameters in this overload.
1.The property to bind to, in this case we are binding the Text property
2. The BindingSource (bindSrc)
3. The member of the DataTable to bind to.
Note: The name of my Form is BindingNavigator
Private Sub BindingNavigator_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = LoadData()
Dim bindSrc As New BindingSource
bindSrc.DataSource = dt
BindingNavigator1.BindingSource = bindSrc
lblItem.DataBindings.Add(New Binding("Text", bindSrc, "name"))
lblDescription.DataBindings.Add(New Binding("Text", bindSrc, "description"))
lblPrice.DataBindings.Add(New Binding("Text", bindSrc, "price"))
End Sub
Private Function LoadData() As DataTable
Dim dt As New DataTable
Using conn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("SELECT name, description, price FROM Food WHERE id LIKE 'F%';", conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
You will then be able to move through the records with the BindingNavigator toolbar.
You are replacing your labels' texts in each iteration. I recommend to use a datagrid instead. However, if you want to use labels anyway, update your loop as this:
lklblItem1.Text += vbNewLine + dr.GetValue(dr.GetOrdinal("name"))
lblDescription.Text += vbNewLine + dr.GetValue(dr.GetOrdinal("description"))
lblPrice.Text += vbNewLine + dr.GetValue(dr.GetOrdinal("price"))

Using corresponding value of picturebox to delete access record

Hey I've created a dictionary that I use to create pictureboxes. Each picturebox has a number, which I then want to use to remove the access record, corresponding to that number. So I've got the dictionary working, but how do I get the number that corresponds to each picturebox? Here is my code (everything is defined, like cardsdictionary as dictionary):
Public Sub bigpictureloader()
'Dim list As New List(Of String)(cardsdictionary.Keys)
Dim cardcount As Integer
cardcount = 0
counter += 1
cardcount = counter
'Dim cards As List(Of String) = New List(Of String)
cardsdictionary.Add(imageurltxt.Text, cardcount)
'Create a placeholder variable
Dim cardPictureBox As PictureBox
Dim pair As KeyValuePair(Of String, Integer)
'Loop through every selected card URL
For Each pair In cardsdictionary
'Create a new PictureBox
cardPictureBox = New PictureBox()
cardPictureBox.Size = New Size(100, 100)
cardPictureBox.SizeMode = PictureBoxSizeMode.Zoom
cardPictureBox.WaitOnLoad = False
AddHandler cardPictureBox.Click, AddressOf imagehandler
'Add the PictureBox to the Form
Me.Controls.Add(cardPictureBox)
'MsgBox(cardsdict.Values.ToString)
If imageurltxt.Text = "" Then
cardPictureBox = Nothing
Else
cardPictureBox.LoadAsync(pair.Key)
TableLayoutPanel1.Controls.Add(cardPictureBox, 0, 0)
End If
Next
End Sub
Private Sub testdelete()
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
'pair.value is what I think will work, but doesn't currently
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(pair.value)
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
this is my imagehandler!!!
Private Sub imagehandler(Sender As Object, e As EventArgs)
testdelete()
End Sub
You can use the Tag property of the PictureBox to store the ID. You populate this property when you create the PictureBox.
In your handler you can do something like this:
Private Sub imagehandler(Sender As Object, e As EventArgs)
Dim myPictureBox As PictureBox = CType(sender, PictureBox)
'Now you can access myPictureBox.Tag and pass it into your delete function
Dim id As Integer = -1
If Int32.TryParse(myPictureBox.Tag, id) = True Then
testdelete(id)
End If
End Sub
Private Sub testdelete(id As Integer)
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
'pair.value is what I think will work, but doesn't currently
command.Parameters.Add("#ID", OleDbType.Integer).Value = id
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
testdelete doesn't know which imasge you want to delete. Using Michael's suggestion you want:
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(Me.Tag)
By the way your use of counter and cardcount can be cleaned up substantially.

Populating a Menu from a Database

I found some very useful code on populating a menu from a database and customised it a bit but I am struggling to create a third level to menu as in the below example(2.1.1 and 2.1.2)
Home
About Us
2.1 Management Team
2.1.1 Team Member 1
2.1.2 Team Member 2
2.2 Company Information
Contact Us
I have listed my code below.
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iconCloud_BL
Partial Class Main
Inherits System.Web.UI.MasterPage
Public Params As New List(Of SqlParameter)
Dim clsDatabase As New clsDatabaseLogic
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData(0, 2)
PopulateMenu(dt, 0, Nothing)
End If
End Sub
Private Function GetData(parentMenuId As Integer, role As Integer) As DataTable
Dim query As String = "SELECT [menusMenuId], [menusTitle], [menusDescription], [menusUrl] FROM [configMenus] WHERE menusParentMenuId = #ParentMenuId AND menusRole = #Role"
Dim constr As String = ConfigurationManager.ConnectionStrings("iconDataConnections").ConnectionString
Using con As New SqlConnection(constr)
Dim dt As New DataTable()
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("#ParentMenuId", parentMenuId)
cmd.Parameters.AddWithValue("#Role", role)
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer, parentMenuItem As MenuItem)
Dim dtChild As DataTable
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim rowcount = getMaxRows()
Dim menuItem As New MenuItem() With {
.Value = row("menusMenuId").ToString(),
.Text = row("menusTitle").ToString(),
.NavigateUrl = row("menusUrl").ToString(),
.Selected = row("menusUrl").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
}
If parentMenuId = 0 Then
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(menuItem.Value), 2)
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
ElseIf parentMenuId > 0 Then
For i As Integer = 0 To rowcount
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(i), 2)
PopulateMenu(dtChild, Integer.Parse(i), menuItem)
Next
Else
parentMenuItem.ChildItems.Add(menuItem)
End If
Next
End Sub
Public Function getMaxRows()
clsDatabase.SQLCmd.CommandText = "sp_iconCloud_configMenuRowsCount"
clsDatabase.SQLCmd.CommandType = CommandType.StoredProcedure
clsDatabase.SQLCmd.Connection = clsDatabase.SQLConn
clsDatabase.SQLConn.Open()
Dim count As Integer = clsDatabase.SQLCmd.ExecuteScalar()
clsDatabase.SQLConn.Close()
clsDatabase.SQLCmd.Parameters.Clear()
Return count
End Function
End Class

Why I am getting System.Data.DataRowViewā€¯ instead of real values from my Listbox in vb.net

Could someone help here?
I need to extract data from a Database into a combolistbox in VB.net. I have got the data, but now find that The first and the 'x' line need to be removed from the combolistbox (they are validation entries for another software) and shouldn't be selected for this application.
I tried to simply remove the offending entries from lists by using :- cbCubeARivet.Items.RemoveAt(index), but had an error letting me know I cannot use "Items" with a DataSource.
I decided to send the data to a listbox, and then try to transfer the entries to the combolistbox. This then lead me to getting multiple entries of System.Data.DataRowView in the combolist box. To demonstrate my problem I include an example code modified from MSDN.
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Populate the list box using an array as DataSource.
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
'Use DataAdapter to fill DataTable
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
'original code from MSDN
'Dim USStates As New ArrayList()
'USStates.Add(New USState("Alabama", "AL"))
'USStates.Add(New USState("Washington", "WA"))
'USStates.Add(New USState("West Virginia", "WV"))
'USStates.Add(New USState("Wisconsin", "WI"))
'USStates.Add(New USState("Wyoming", "WY"))
'ListBox1.DataSource = USStates
' Set the long name as the property to be displayed and the short
' name as the value to be returned when a row is selected. Here
' these are properties; if we were binding to a database table or
' query these could be column names.
' Bind the SelectedValueChanged event to our handler for it.
AddHandler ListBox1.SelectedValueChanged, AddressOf ListBox1_SelectedValueChanged
' Ensure the form opens with no rows selected.
ListBox1.ClearSelected()
End Sub 'NewNew
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs)
If ListBox1.SelectedIndex <> -1 Then
TextBox1.Text = ListBox1.SelectedValue.ToString()
' If we also wanted to get the displayed text we could use
' the SelectedItem item property:
' Dim s = CType(ListBox1.SelectedItem, USState).LongName
End If
End Sub
End Class 'ListBoxSample3
Public Class USState
Private myShortName As String
Private myLongName As String
Public Sub New(ByVal strLongName As String, ByVal strShortName As String)
Me.myShortName = strShortName
Me.myLongName = strLongName
End Sub 'NewNew
Public ReadOnly Property ShortName() As String
Get
Return myShortName
End Get
End Property
Public ReadOnly Property LongName() As String
Get
Return myLongName
End Get
End Property
End Class 'USState
I may not get this correct so here goes, the following uses mocked up data to display a string in both a ListBox and ComboBox where a integer is available by casting the current item as a DataRowView, access Row then access the data via Row.Field(Of Integer)("ID").
In the code I use a copy of the underlying DataTable for the ComboBox as using the same data table for listbox and combobox will cause one to traverse when is generally unwanted. The cast aspect would be done in another event but wanted to stay simple. Again I may not be on track here, let me know and can adjust to better suit your question.
Code using Option Infer On for the Linq anonymous statement which could be strongly typed too.
Dim dt As New DataTable
dt.Columns.Add(New DataColumn With {.ColumnName = "ID", .DataType = GetType(Integer)})
dt.Columns.Add(New DataColumn With {.ColumnName = "Name", .DataType = GetType(String)})
Dim data =
(
From M In System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
Where Not String.IsNullOrEmpty(M)).ToList.Select(
Function(monthName, index) New With
{
.ID = index, .Name = monthName
}
).ToList
For Each item In data
dt.Rows.Add(New Object() {item.ID, item.Name})
Next
ListBox1.DataSource = dt
ListBox1.DisplayMember = "Name"
ComboBox1.DataSource = dt.Copy
ComboBox1.DisplayMember = "Name"
Dim theTable As DataTable = CType(ComboBox1.DataSource, DataTable)
Dim theRow As DataRow = theTable.AsEnumerable _
.Where(
Function(row) row.Field(Of String)("Name") = "September") _
.FirstOrDefault()
If theRow IsNot Nothing Then
theTable.Rows.Remove(theRow)
End If
Thanks again #Karen Payne,
I used your code to lead me in the right direction.
I created a new application and added a textbox, and two Listboxes, then paste the code. To run you will need to point to your own Server, Database, and Table.
This is what I came up with. It is useful as this will give you the actual data in a useable form:-
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' get the data
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
' Populate the list box using an array as DataSource.
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
' remove validation data from list
Dim Count As Integer
Dim X As Integer
'get the column of data to search for
For Count = 0 To ListBox1.DataSource.Columns.Count - 1
X = InStr(ListBox1.DataSource.Columns.Item(Count).ToString, "Name")
If X <> 0 Then Exit For
Next
' now search for any invalid rows, in that column. those containing "---"
Dim TheTable As DataTable = CType(ListBox1.DataSource, DataTable)
Dim theRow As DataRow() = TheTable.Select()
Dim RowNumber As Integer
For RowNumber = 0 To UBound(theRow) - 1
If theRow(RowNumber).Item(Count).ToString <> "---" Then
' data is OK so transer it to the other listbox
ListBox2.Items.Add(theRow(RowNumber).Item(Count - 1).ToString)
End If
Next
ListBox2.ClearSelected()
End Sub 'NewNew
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
TextBox1.Text = ListBox2.SelectedItem.ToString()
End Sub
End Class 'ListBoxSample3