ListBox index changed shows wrong value from SQLite database - vb.net

I am coding a VB.NET program, which uses SQLite as a database.
My problem is when the form is loading it is displaying all values from a particular column (questions in my case) from the database to the ListBox. Then if the user clicks on any item (ListBox index change), the corresponding value from the database (answer) displays in a RichTextBox. This works as expected.
When the user types something in a TextBox and clicks the search Button, it is expected to show the questions from the database according to TextBox.Text as a tag column in the database to the same ListBox. This also works fine.
The problem begins when the ListBox index changes now. If the search result is only one item in the ListBox, the index will be zero and the RichTextBox shows the first item of the database insted of the corresponding value of the ListBox item.
My code is here:
Sub showData()'''this shows questions when form loads
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String = "select * from elect"
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
'sqConnection.Open()
Try
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
' Always call Read before accessing data.
Do While sqReader.Read()
Dim sName = sqReader.Item("question")
ListBox1.Items.Add(sName)
Loop
' always call Close when done reading.
sqReader.Close()
' Close the connection when done with it.
Finally
connection.Close()
End Try
End Sub
Public Sub NavigateRecords()
page1.Clear()''page is rich text box
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String
mySelectQuery = "select * from elect"
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
Dim num As Integer = Me.inc = Conversions.ToInteger(ListBox1.SelectedIndices.ToString)
MsgBox(num)
Me.inc = Conversions.ToInteger(ListBox1.SelectedIndex.ToString)
If (Me.inc > -1) Then
Dim ans As String = Conversions.ToString(ds.Tables.Item("elect").Rows.Item(Me.inc).Item(2))
page1.Text = (ans)
End If
End Sub
Private Sub search()
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String = ("select * from elect WHERE tag like'%" & txtSearch.Text & "%' ")
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
Try
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
' Always call Read before accessing data.
Do While sqReader.Read()
Dim sName = sqReader.Item("question")
ListBox1.Items.Add(sName)
Loop
If ListBox1.Items.Count = 0 Then
MsgBox("Nothing Found ")
showData()
End If
' always call Close when done reading.
sqReader.Close()
' Close the connection when done with it.
Finally
connection.Close()
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
page1.Visible = True
ListBox1.Visible = False
Label1.Visible = False
NavigateRecords()
End Sub

Related

fill a dataGridView with content from an Access db with a relationship

Im having trouble getting the correct data to display in a DataGridView. I have two tables (Student) and (Module) in an access db, I have the text boxes displaying the data from the Student tables but i need the DataGridView to display their corresponding modules. the code is
Public Class frnMain
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = Students.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * From Student", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDataSet As New DataSet()
Dim objModuleDA As New OleDb.OleDbDataAdapter("Select * from Student", objConnection)
Dim objModuleCB As New OleDb.OleDbCommandBuilder(objModuleDA)
Dim Counter As Integer = 1
Private Sub frnMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Retrieve()
FillStudentDetails()
End Sub
Public Sub Retrieve()
objDataSet.Clear()
objStudentDA.FillSchema(objDataSet, SchemaType.Source, "Student")
objStudentDA.Fill(objDataSet, "student")
objModuleDA.FillSchema(objDataSet, SchemaType.Source, "Module")
objModuleDA.Fill(objDataSet, "Module")
'Set Relationships
objDataSet.Relations.Clear()
objDataSet.Relations.Add("student2Module", objDataSet.Tables("Student").Columns("StudentId"),
objDataSet.Tables("Module").Columns("StudentId"))
End Sub
Public Sub FillStudentDetails()
Dim objrow As DataRow
Dim objModule As DataRow
objrow = objDataSet.Tables("Student").Rows.Find(Counter)
objModule = objDataSet.Tables("Module").Rows.Find(Counter)
mtbStudentId.Text = objrow.Item("StudentId")
txtName.Text = objrow.Item("StudentName")
txtAddress.Text = objrow.Item("StudentAddress")
For Each objModules In objrow.GetChildRows("Student2Module")
dgvModule.DataSource = objDataSet.Tables(0)
Next
End Sub
I know the code is wrong in the for loop at the end I was just experimenting to see if i could get it. thanks in advance.
I fixed it by using fixed columns and just looping through the other table
dgvModule.ColumnCount = 3
dgvModule.Columns(0).Name = "Module ID"
dgvModule.Columns(1).Name = "Module Name"
dgvModule.Columns(2).Name = "Student Id "
dgvModule.Rows.Clear()
For i As Integer = 1 To objDataSet.Tables("Module").Rows.Count
objModule = objDataSet.Tables("Module").Rows.Find(i)
If currentId = objModule.Item("StudentId") Then
Dim row As String() = New String() {(objModule.Item("ModuleId")), objModule.Item("ModuleName"), objModule.Item("StudentId")}
dgvModule.Rows.Add(row)
Else
End If
Next

Dataadapter update with VB

I hope some vb expert could tell me what I am doing wrong.
I am trying to open, modify and update a record in Northwind MDF.
The DA.Update(DS) statement always generate an error.
I find several examples on the net but only in C and thatI dond’t understand, only work in VB. I find myself so stuppid not to understand the update mechanism.
My source:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Call GETNWDS()
ContactNamebox.Text = ContactNamebox.Text + " " + Now
Call UpdateNWDS()
End If
End Sub
Public Sub GETNWDS()
'' open custumor DataAdapter daaset DS
Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"
Dim CN As New SqlConnection(connectionString)
Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
Dim DS As DataSet = New DataSet
DA.Fill(DS)
Dim DT As DataTable = DS.Tables(0)
Dim row As DataRow = DT(0)
CustomerIDbox.Text = row("CustomerID").ToString
CompanyNamebox.Text = row("CompanyName").ToString
ContactNamebox.Text = row("ContactName").ToString
CN.Close()
End Sub
Public Sub UpdateNWDS()
Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"
Dim CN As New SqlConnection(connectionString)
Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
Dim DS As DataSet = New DataSet
DA.Fill(DS)
Dim DT As DataTable = DS.Tables(0)
Dim row As DataRow = DT(0)
row("CustomerID") = CustomerIDbox.Text
row("CompanyName") = CompanyNamebox.Text
row("ContactName") = ContactNamebox.Text
Textbox.Text = row("ContactName").ToString
' DA.Update(DS) ' skip to avoud error
CN.Close()
End Sub
The webform is being filled with 3 DB items.
Then 1 box is changed and the update toutineis called but there is an error on the update statement.
Skippimg this statement shows this webform.
Note that the new row value is displalyed in a textbox.

Filtering SQL data by ListBox item to display in DataGridViews

I can't get the listbox item to filter properly.
Basically, I want to click an item in my ListBox and that will populate the DataGridView accordingly. I have 2 DataGridViews which will display different criteria based on the ListBox item selected.
My code so far is the following:
Public Class Form1
Dim str As String = "Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True"
Dim con As New SqlConnection(Str)
Dim com As String = "Select swname, numoflic from SW2"
Dim com2 As String = "Select name, instdate, swinsta, organ from Assigned2"
Dim Adpt As New SqlDataAdapter(com, con)
Dim Adpt2 As New SqlDataAdapter(com2, con)
Dim ds, ds2 As New DataSet()
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim dt As DataTable
dt = New DataTable("SW2")
'DEFINING LISTBOX ITEM AS STRING
Dim curItem As String = ListBox1.SelectedItem.ToString()
ds.Tables.Clear()
ds2.Tables.Clear()
Adpt.Fill(ds, "ContactPerson2")
DataGridView1.DataSource = ds.Tables(0)
Adpt2.Fill(ds2, "Assigned2")
DataGridView2.DataSource = ds2.Tables(0)
End Sub
You'll need to filter your data set as explained here. Also, I'd recommend you don't refill your datatables in the event handler. Load them both in Form_Load and then just pass Nothing to the filter to clear any prior filters in the beginning of the SelectedIndexChanged event handler.
I changed the code around a bit and what works for me now is the code below.
Dim curItem As String = ListBox1.SelectedItem(1)
Dim sqlConnectionString As String = "Data Source=XXXX;Initial Catalog=XXXXX;Integrated Security=True"
Dim sqlSelect As String = "Select swname, number from SW"
Dim da As New SqlDataAdapter(sqlSelect, sqlConnectionString)
Dim dt As New DataTable
da.Fill(dt)
'filter setting defined here
Dim filter As String = "swname = '" + curItem + "'"
'filter rows
Dim FilteredRows As DataRow() = dt.Select(filter)
For Each row As DataRow In FilteredRows
DataGridView1.DataSource = FilteredRows.CopyToDataTable()
Next

"This row already belongs to this table"

I've read existing code in stackoverflow but I'm still lost as how do I fix this.
This row already belongs to this table.
Any suggestions always is appreciated.
It errors out on my command button save event.
I've listed code for the entire form just to give you an idea on what I'm doing. Hope this helps
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
DataGridView1.EndEdit()
Dim con As SqlConnection = CompDB.GetConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim SPgetStandards As String = "dbo.SPgetStandards"
Dim SPgetRecordDetail As String = "dbo.SPgetRecordDetail"
Dim dsStandard As New DataSet
Dim dsRecords As New DataSet
Dim currentrow As DataRow
Dim currentcolumn As DataColumn
MsgBox("Record id is " & RecordID)
Using con
con.Open()
Dim Standardsdataadapter As New SqlClient.SqlDataAdapter(SPgetStandards, con)
Dim Detaildataadapter As New SqlClient.SqlDataAdapter(SPgetRecordDetail, con)
Detaildataadapter.Fill(dsRecords, "Record")
Standardsdataadapter.Fill(dsStandard, "Standard")
'5/31/13
'Figured out how to run a loop through a table and write to the console
For Each currentrow In dsStandard.Tables("Standard").Rows
For Each currentcolumn In dsStandard.Tables("Standard").Columns
'Debug.WriteLine(currentrow(currentcolumn) & ControlChars.Tab & ControlChars.Tab)
'MsgBox(currentcolumn.ToString)
'Debug.WriteLine(currentrow.Item(0))
Next currentcolumn
Next currentrow
' con.Close()
'con.Dispose()
Dim newrow As DataRow = dsRecords.Tables("Record").NewRow
For Each oRow As DataGridViewRow In DataGridView1.Rows
If Convert.ToInt16(oRow.Cells("chkbox").Value) = 1 Then
' Debug.WriteLine("It was clicked ", DataGridView1.Columns.Item(1))
Debug.WriteLine(oRow.Cells("ID").Value)
'dsStandard.Tables.Add.Rows("RecordID") = 1234
'dsRecords.Tables.Add.Rows("Standard_Name_ID") = 1234
' newrow("Record_Detail_ID") = RecordID
' newrow("Record_ID") = RecordID
newrow("Standard_Name_ID") = (oRow.Cells("ID").Value)
'/////Errors out here!!!!!dsRecords.Tables("Record").Rows.Add(newrow) '/////Errors out here!!!!!
dsRecords.AcceptChanges()
End If
Next
End Using
End Sub
Move this line:
Dim newrow As DataRow = dsRecords.Tables("Record").NewRow
To be the first line inside of your If block.

Showing all fields in listbox from database, vb.net

I'm trying to make a list box to show all the fields of a particular table in an Access database. I have a few tables, and the idea would be to have each table loaded by a different button (and the items in the box cleared). One trick is that tables aren't all the same size. How do I get all the fields to show up for each table. What I have now is only showing one field:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source='C:\dummy_data.accdb';"
Dim conn As New OleDbConnection(connString)
Dim sql As String = "SELECT * FROM Customers"
Dim cmd As New OleDbCommand(sql, conn)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
ClientList.Items.Clear()
While reader.Read()
ClientList.Items.Add(reader(0).ToString())
End While
reader.Close()
conn.Close()
End Sub
If you are not averse to using a DataGridView instead of a ListView, you could do it this way:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;data source='PathToMyDatabase';"
Dim sql As String = "SELECT * FROM Tメイン;"
Dim dt As DataTable
With New OleDbDataAdapter(sql, connString)
Dim ds As New DataSet()
.Fill(ds)
dt = ds.Tables(0)
End With
Me.DataGridView1.DataSource = dt
I do not have 'ACE.OLEDB' on my computer, so had to use the JET provider instead, but it should work the same way.
I should add that you can use this method to retrieve the data from the DB, but there is no easy way as far as I understand to bind a DataTable to a ListView (see this MSDN question for example) and you would have to loop through the columns in your DataTable first and add the column headers to your ListView and then loop through the rows and add the data.
UPDATE:
To answer your questiona s to how to export data from the DataGridView I remembered that I wrote code to do that a little while back.
Private Function ExportToExcelFile(ByVal FileName As String) As Boolean
With New Excel.Application
With .Workbooks.Add()
For Each sheet As Worksheet In .Worksheets
If sheet.Index > 1 Then
Call sheet.Delete()
End If
Next
With CType(.Worksheets(1), Worksheet).Range("A1")
For Each column As DataGridViewColumn In Me.dgvData.Columns
.Offset(0, column.Index).Value = column.HeaderText
For Each row As DataGridViewRow In Me.dgvData.Rows
.Offset(row.Index + 1, column.Index).Value = row.Cells(column.Index).Value
Next
Next
End With
Call .SaveAs(FileName)
End With
Call .Quit()
End With
End Function
I hope this will help to get you started.
Using a Listview control, the following code should do the trick. For simplicity I defined only 4 customer fields - you will need to define them according to your table field defintions:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ClientList.View = View.Details
ClientList.FullRowSelect = True
ClientList.Columns.Add("ID", 120)
ClientList.Columns.Add("Name", 120)
ClientList.Columns.Add("Address", 140)
ClientList.Columns.Add("Email", 100)
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\dummy_data.accdb;"
ClientList.Items.Clear()
Using conn As New Data.OleDb.OleDbConnection(connString)
conn.Open()
Dim sql As String = "SELECT * FROM Customers"
Using cmd As New Data.OleDb.OleDbCommand(sql, conn)
Dim lvi As ListViewItem
Using oRDR As Data.OleDb.OleDbDataReader = cmd.ExecuteReader
While oRDR.Read()
lvi = ClientList.Items.Add(oRDR.GetValue(0).ToString)
For i = 1 To oRDR.FieldCount - 1
lvi.SubItems.Add(oRDR.GetValue(i).ToString)
Next
End While
End Using
End Using
conn.Close()
End Using
End Sub