fill a dataGridView with content from an Access db with a relationship - vb.net

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

Related

ListBox index changed shows wrong value from SQLite database

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

Populating Textbox and DropdownLists

I am having a hard time trying to populate a textbox, and two dropdown lists. What I am attempting to do is this: when the Company dropdownlist has been selected, it will display a grid of its respective values from a sqldatasource, which it does. Now the next step is once a selection from the company dropdown has been made, a textbox will display the membertype as well as the second dropdownlist. The third dropdown displays the groupid. All these three components have their outputs after a selection has been made. But I cannot seem to get the values to show. I also added code for clarification.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls
Partial Class companydropdown
Inherits System.Web.UI.Page
Private Sub BindDropDownList(DropdownList1 As DropDownList, query As String, text As String, value As String, defaultText As String)
If Not IsPostBack Then
' Read sql server connection string from web.config file
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
'da.Fill(dt)
End Using
'DropdownList1.DataSource = dt
DropdownList1.DataTextField = "CompanyName"
DropdownList1.DataValueField = "CompanyID"
DropdownList1.DataBind()
'DropdownList1.Items.Insert(0, New ListItem("--Select--"))
End If
End Sub
Protected Sub Member_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList2.DataTextField = "MembershipStatus"
DropDownList2.DataValueField = "MemberTypeID"
' Bind sql server data into the Dropdown List
DropDownList2.DataBind()
Else
DropDownList2.Items.Clear()
End If
End Sub
Protected Sub Group_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList3.DataTextField = "GroupID"
DropDownList3.DataValueField = "GroupID"
' Bind sql server data into the Dropdown List
DropDownList3.DataBind()
Else
DropDownList3.Items.Clear()
End If
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
DropDownList2.Enabled = False
'DropDownList3.Items.Clear()
DropDownList3.Items.Insert(0, New ListItem("", "0"))
Dim stateId As Integer = Integer.Parse(DropDownList1.SelectedItem.Value)
If stateId > 0 Then
Dim query As String = String.Format("", stateId)
BindDropDownList(DropDownList1, query, "CompanyName", "CompanyId", "")
DropDownList3.Enabled = True
DropDownList2.Enabled = True
End If
End Sub
End Class

Display image from database in a datagrid with vb.net

I'm using a MySql database with 2 fields: a dossiernumber and a field where I save the name and location of a image. I want to place a datagrid on my winform and show a image (thumbnail) in the first cell and the dossiernumber in the second cell, but can't get it working.
The pictures don't show and leave only missing picture link. I also can't place the picture in the first cell. This is what it looks like:
What is wrong?
This is the code I've written:
Imports MySql.Data.MySqlClient
Public Class Form1
'ALLES OM DATAGRID TE PLAATSEN
'GLOBALE DECLARATIES
Dim conString As String = "server=localhost;userid=root;database=testvehicle"
Dim con As New MySqlConnection(conString)
Dim cmd As MySqlCommand
Dim adapter As MySqlDataAdapter
Dim dt As New DataTable()
Private Sub Form1_GotFocus(sender As Object, e As EventArgs) Handles Me.GotFocus
retrieve()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 2
DataGridView1.Width = 410
'CONSTRUCT IMAGE COLUMN
Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
DataGridView1.Columns(0).Name = "Image"
DataGridView1.Columns.Add(imgCol)
'CONSTRUCT DATA COLUMNS
DataGridView1.Columns(1).Name = "dossiernr"
DataGridView1.Columns(1).Width = 100
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
End Sub
'ALLES OM DATAGRID TE VULLEN
'PROCEDURE POPULATE ROW
Private Sub populate(foto1 As String, product_dossiernr As String)
Dim row As String() = New String() {foto1, product_dossiernr}
'ADD ROW TO ROWS
DataGridView1.Rows.Add(row)
End Sub
'DATA ONTVANGEN
Private Sub retrieve()
DataGridView1.Rows.Clear()
'SQL STATEMENT
Dim sql As String = "SELECT foto1, product_dossiernr FROM producten ORDER BY product_dossiernr"
cmd = New MySqlCommand(sql, con)
'OPEN CON, RETRIEVE, FILL DATAGRID
Try
con.Open()
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(dt)
For Each row In dt.Rows
populate(row(0), row(1))
Next
con.Close()
dt.Rows.Clear()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
'EINDE DATAGRID VULLEN
End Class
in your code it looks like your naming your column the image name, not assigning it a picture value so this is why your getting the name and not the image.
here is s snippet of code I used before that works pretty well.
Dim ColImage As New DataGridViewImageColumn
Dim Img As New DataGridViewImageCell
'Set Name
ColImage.Name = "ColImg"
'Set Header text
ColImage.HeaderText = "Your Image!"
'Add column to datagridview
DataGridView1.Columns.Add(ColImage)
'Set image value
Img.Value = Image.FromFile("C:\YourImage.png")
'Add the image cell to a row
DataGridView1.Rows(0).Cells.Add(Img)

VB.NET & SQL Server database : adding record from textbox

I am trying to make a highscore table that will take the users name from textbox and grab the score from a label on another form and store them into a database called highscores. I can get the connection to work but I can't figure out how to add the records I need added and display them in the datagrid view.
Private MyDatAdp As New SqlDataAdapter
Private MyCmdBld As New SqlCommandBuilder
Private MyDataTbl As New DataTable
Private MyCn As New SqlConnection
Private MyRowPosition As Integer = 0
Private Sub highscore_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyCn.ConnectionString = "Data Source=(localDB)\v11.0;AttachDbFilename=C:\Users\Scores.mdf;integrated security = true;Connect Timeout = 30"
MyCn.Open()
MyDatAdp = New SqlDataAdapter("Select* from HighScores", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)
Dim MyDataRow As DataRow = MyDataTbl.Rows(1)
Dim MyDataRow2 As DataRow = MyDataTbl.Rows(2)
Dim Name As String
Dim Score As String
Name = MyDataRow("Name")
Score = MyDataRow2("Score")
NameBox.Text = Name.ToString
Math.Score.Text = Score.ToString
Me.showRecords()
End Sub
Private Sub showRecords()
If MyDataTbl.Rows.Count = 0 Then
NameBox.Text = ""
Math.Score.Text = ""
Exit Sub
End If
NameBox.Text = MyDataTbl.Rows(MyRowPosition)("Name").ToString
Math.Score.Text = MyDataTbl.Rows(MyRowPosition)("Score").ToString
End Sub
End Class

TreeView Leaf Node Not Remained Opened

I Have Following Code to load a Treeview from DB Problem is That When I Click On Leaf Node It Collapse Into the Parent Node Any One Please tell me How can I set the Leaf Node To Be Remained Open
update Code
This My Complete code Through whic i am Populating my Treeview
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
fill_Tree2()
End Sub
Private Sub fill_Tree2()
Dim PrSet As DataSet = PDataset("Select * from GPS_TREE_PROV")
TreeView1.Nodes.Clear()
For Each dr As DataRow In PrSet.Tables(0).Rows
Dim tnParent As New TreeNode()
tnParent.Text = dr("Prov_name").ToString()
tnParent.Value = dr("prov_id").ToString()
tnParent.PopulateOnDemand = False
tnParent.SelectAction = TreeNodeSelectAction.Expand
tnParent.Expand()
tnParent.Selected = True
tnParent.ToolTip = tnParent.Text
'tnParent.CollapseAll()
TreeView1.Nodes.Add(tnParent)
FillChild(tnParent, tnParent.Value)
Next
End Sub
Public Sub FillChild(ByVal parent As TreeNode, ByVal ParentId As String)
Dim ds As DataSet = PDataset("Select * from GPS_Tree_STA where Prov_ID =" & ParentId)
parent.ChildNodes.Clear()
Dim tnParent As New TreeNode()
For Each dr As DataRow In ds.Tables(0).Rows
Dim child As New TreeNode()
child.Text = dr("sta_name").ToString().Trim()
child.Value = dr("sta_id").ToString().Trim()
'If Not child.ChildNodes.Count = 0 Then
' child.PopulateOnDemand = False
'End If
child.ToolTip = child.Text
'child.SelectAction = TreeNodeSelectAction.Select
'child.CollapseAll()
'child.Expand()
parent.ChildNodes.Add(child)
FillChild1(child, child.Value)
Next dr
End Sub
Public Sub FillChild1(ByVal parent1 As TreeNode, ByVal ParentId1 As String)
Dim ds As DataSet = PDataset("Select * from GPS_Tree_TEHS where STA_ID =" & ParentId1)
parent1.ChildNodes.Clear()
For Each dr1 As DataRow In ds.Tables(0).Rows
Dim child1 As New TreeNode()
child1.Text = dr1("tehs_name").ToString().Trim()
child1.Value = dr1("tehs_id").ToString().Trim()
'If Not child1.ChildNodes.Count = 0 Then
' child1.PopulateOnDemand = False
' child1.Expand()
'End If
child1.ToolTip = child1.Text
child1.SelectAction = TreeNodeSelectAction.Select
child1.Expanded = True
parent1.ChildNodes.Add(child1)
Next
End Sub
Protected Function PDataset(ByVal Select_Statement As String) As DataSet
Dim SqlCon As New OleDbConnection
SqlCon = New OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle")
Dim da As New OleDbDataAdapter(Select_Statement, SqlCon)
Dim ds As New DataSet()
da.Fill(ds)
Return ds
End Function
Please Any One Tell me How can I set the Leaf Node as Remained Open When It Clicks On it through this code
It is difficult to understand the logic, since you didn't provide the code related to events, but from a glance to the code you should try to remove the line
child1.Collapse()
from procedure
FillChild1