vb.net CheckedListbox get value from database - vb.net

I am populating a CheckedListBox from a MsAccess database table. The table consists of two fields, Terms and RegX. I want to display Terms but when I submit I want to get the value form the RegX field.
Public Function GetMyTable() As DataTable
' Create new DataTable instance.
Dim table As New DataTable
Dim strSql As String = "SELECT * FROM Keywords ORDER BY Terms ASC"
Dim cmd As New OleDbCommand(strSql, con)
Using dr As OleDbDataReader = cmd.ExecuteReader
table.Load(dr)
End Using
Return table
End Function
Private Sub SearchInDoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt1 As DataTable = GetMyTable()
If dt1.Rows.Count > 0 Then
For i As Integer = 0 To dt1.Rows.Count - 1
CheckedListBox1.Items.Add(CStr(dt1.Rows(i).Item("Terms")), False)
Next
End If
CheckedListBox1.CheckOnClick = True
End Sub
I dont know how to return the value of RegX when I click my Submit button

If you want to keep together the information about "Terms" and "RegX" then you should use the DataSource property of the CheckedListBox setting it with the datatable retrieved and then specify what column should be showed in the list.
Private Sub SearchInDoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt1 As DataTable = GetMyTable()
CheckedListBox1.DataSource = dt1
CheckedListBox1.DisplayMember = "Terms"
CheckedListBox1.CheckOnClick = True
End Sub
Now in your submit button you could add code like this to retrieve the RegX field
Sub Submit_Click(sender As Object, e As EventArgs) Handles Submit.Click
For Each row As DataRowView In CheckedListBox1.CheckedItems
Console.WriteLine(row("RegX"))
Next
End Sub
Each element in the CheckedListBox is a DataRowView taken from the table and you can extract the information about the RegX field simply indexing that DataRowView with the name of the column.
In the example above only the checked items are subject to the loop enumeration. If you want to traverse all the items in the CheckedListBox use CheckedListBox1.Items

Related

how to read a random entity in a database

I was just wondering how I would display a random entity in an access column.
Imports System.Data.OleDb
Public Class ReviseFlashcards
Dim connection As New OleDb.OleDbConnection(
"provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb")
Dim dt As New DataTable
Dim dataadapter As OleDb.OleDbDataAdapter
'contains the current row number
Dim rownumber As Integer = 0
'Data table to contain all the records
Private Sub ReviseFlashcards_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
Dim sqlstring As String = "select * from flashcards"
connection.Open()
dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
dt.Clear()
dataadapter.Fill(dt)
txtFront.Text = dt.Rows(0)(2)
txtBack.Text = dt.Rows(0)(3)
connection.Close()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) _
Handles btnDisplay.Click
End Sub
End Class
The current code displays the first row in the database which is shown below. I was wondering if there was a way to display a random row by clicking a button with the front and back matching each other.
The access database
Add a random generator to the form. Make shure to declare it as Shared, so that this generator will be created only once. This ensures that it generates unique random number sequencess (see: Why isn't this Random number generation code working?).
Private Shared rand As New Random()
Then create a row index by respecting the actual row count:
Dim index = rand.Next(dt.Rows.Count) ' generates index in the range 0 .. Count - 1
txtFront.Text = dt.Rows(index)(2).ToString()
txtBack.Text = dt.Rows(index)(3).ToString()

ifselectedindex changed , show data in a textbox

I've linked an access database to my form.
I have 1 table , 2 rows
1 = Researchtype short text
2 = Researchdetails (long text)
In my combobox1 i've binded my researchtype row so i can choose a type of research.
Question now: how can i bind the details data to the richtextbox below it in order to show the research data as soon as i choose a research type?
I've tried if else combos, try catch combos,
i'm thinking i'm actually overthinking the issue here.
What would be the easiest way to "select from dropdown" and show the result in textbox.
I'm a vb.net beginner
Public Class Onderzoeken
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PatientenDatabaseDataSetX.tbl_OnderzoeksTypes' table. You can move, or remove it, as needed.
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
End Sub
Private Sub cboxOnderzoek_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectedIndexChanged
If cboxOnderzoek.SelectedItem = Nothing Then
cboxOnderzoek.Text = ""
Else
rtbBeschrijvingOnderzoek.Text = CStr(CType(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving"))
End If
End Sub
End Class
I added the entire code of that page now , it's not much, but as stated: I added the binding source and displaymember "researchtype" to the combobox.
So when i start the form, i can choose a type of research.
Now i need to show the description of the research in the richtextbox
In the Form.Load...
I have a function that returns a DataTable that contains columns called Name and Type. I bind the ComboBox to the DataTable and set the DisplayMember to "Name". Each Item in the ComboBox contains the entire DataRowView. I set the TextBox to the first row (dt(0)("Type")) Type column value so the correct information will be displayed for the initial selection.
I put the code to change the textbox display in ComboBox1.SelectionChangeCommitted because the other change events will produce a NRE since .SelectedItem has not yet been set when the form loads. The commited event will only occur when the user makes a selection.
First, cast the SelectedItem to its underlying type, DataRowView. Then you want the value of the Type column. This value is assigned to the text property of the textbox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = LoadCoffeeTable()
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
TextBox1.Text = dt(0)("Type").ToString
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
TextBox1.Text = DirectCast(ComboBox1.SelectedItem, DataRowView)("Type").ToString
End Sub
Just substitute Researchtype for Name and Researchdetails for Type.
After using 'OleDbDataAdapter' to fill the dataset, you can set 'DisplayMember' and 'ValueMember' for your ComboBox. Every time the index of your ComboBox changes, it's 'ValueMember' will be displayed in richtextbox.
Here's the code you can refer to.
Private dataset As DataSet = New DataSet()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connString As String = "your connection String"
Using con As OleDbConnection = New OleDbConnection(connString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Researchtype, Researchdetails FROM yourtable"
Dim adpt As OleDbDataAdapter = New OleDbDataAdapter(cmd)
adpt.Fill(dataset)
End Using
ComboBox1.DisplayMember = "Researchtype"
ComboBox1.ValueMember = "Researchdetails"
ComboBox1.DataSource = dataset.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
RichTextBox1.Text = ComboBox1.SelectedValue.ToString()
End Sub
Result of my test.

Indicate combobox values with a specific ids?

I made a Sub that will populate my combobox with loan descriptions. I want to get the loancode of the loandescription on selectedindexchanged without querying again the database. Is this possible? Or should I query the database to get the indicated loancode?
Private Sub LoanProducts()
Using cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSQlConn)
Dim dt As New DataTable
Dim da As New SqlClient.SqlDataAdapter
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
For Each row As DataRow In dt.Rows
CmbLoanAvail.Items.Add(row("loandescription"))
Next row
End Using
End Sub
Expected output:
Everytime the combobox index changed, the loancode of the selected loandescription will be displayed to a textbox.
Set DataTable to combobox .DataSource property and populate .ValueMember and .DisplayMember properties with corresponding column names.
Private Sub LoanProducts()
Dim query As String = "SELECT loancode, loandescription FROM LoanProducts"
Using command As New SqlCommand(query, gSQlConn)
Dim data As New DataTable
Dim adapter As New SqlClient.SqlDataAdapter With
{
.SelectCommand = cmd
}
adapter.Fill(data)
CmbLoanAvail.ValueMember = "loancode"
CmbLoanAvail.DisplayMember = "loandescription"
CmbLoanAvail.DataSource = data
End Using
End Sub
You can use SelectionChangeCommitted event to execute some action when user made a selection
Private Sub comboBox1_SelectionChangeCommitted(
ByVal sender As Object, ByVal e As EventArgs) Handles comboBox1.SelectionChangeCommitted
Dim combobox As ComboBox = DirectCast(sender, ComboBox)
Dim selectedCode As String = combobox.SelectedValue.ToString() // returns 'loancode'
End Sub
If you could get DB rows as strongly typed classes, you could make use of ItemSource, DisplayMember and ValueMember, which would solve your problem.
In case you presented, you can use SelectedIndex property of ComboBox. Also, you need to store resultset in some class field (preferably Pirvate one). See example code below:
Public Class Form4
Private _result As DataTable
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("col1")
dt.Columns.Add("col2")
dt.Rows.Add("val11", "val12")
dt.Rows.Add("val21", "val22")
' at this point, we got our result from DB
_result = dt
For Each row As DataRow In dt.Rows
ComboBox1.Items.Add(row("col1"))
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim selectedIndex = ComboBox1.SelectedIndex
Dim selectedRow = _result(selectedIndex)
End Sub
End Class
Keep your database objects local to the method where they are used so you can ensure that they are closed and disposed. Note the comma at the end of the first Using line. This includes the command in the same Using block.
Set the DataSource, DisplayMember and ValueMember after the Using block so the user interface code doesn't run until the connection is disposed.
To get the loan code you simply access the SelectValue of the ComboBox.
Private Sub LoanProducts()
Dim dt As New DataTable
Using gSqlConn As New SqlConnection("Your connection string"),
cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSqlConn)
gSqlConn.Open()
dt.Load(cmd.ExecuteReader)
End Using
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "loandescription"
ComboBox1.ValueMember = "loancode"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
MessageBox.Show($"The Loan Code is {ComboBox1.SelectedValue}")
End Sub

Edit Selected Datagridview Row vb.Net

I have a Datagridview grid with four columns. When a cell is double-clicked, the data on the selected row is passed to four textboxes for the user to make changes if any.So how do i pass the changes made to the selected row instead of having the changes added as new row?
P.S. The Data isn't from a database
You can either "remember" the DataGridViewRow by setting a module-level variable, or you can find the row again by looking for its primary key.
Public Class Form1
'Add to form:
' DataGridView called DataGridView1
' 4 Textboxes called TextBox1, TextBox2, TextBox3, and TextBox4
' Button called btnEdit
' Button called btnSave
Private mintRowWeAreEditing As Integer = -1
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If DataGridView1.DataSource Is Nothing Then
'set initial data
Dim dtb As New DataTable
dtb.Columns.Add("Col1")
dtb.Columns.Add("Col2")
dtb.Columns.Add("Col3")
dtb.Columns.Add("Col4")
dtb.Rows.Add("R1C1", "R1C2", "R1C3", "R1C4")
dtb.Rows.Add("R2C1", "R2C2", "R2C3", "R2C4")
dtb.Rows.Add("R3C1", "R3C2", "R3C3", "R3C4")
dtb.Rows.Add("R4C1", "R4C2", "R4C3", "R4C4")
DataGridView1.DataSource = dtb
End If
'copy data from grid to textboxes
mintRowWeAreEditing = DataGridView1.CurrentCell.RowIndex
Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row
TextBox1.Text = drw("Col1").ToString
TextBox2.Text = drw("Col2").ToString
TextBox3.Text = drw("Col3").ToString
TextBox4.Text = drw("Col4").ToString
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'copy data from textboxes to grid
If mintRowWeAreEditing = -1 Then Exit Sub 'haven't clicked Edit button yet
Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row
drw("Col1") = TextBox1.Text
drw("Col2") = TextBox2.Text
drw("Col3") = TextBox3.Text
drw("Col4") = TextBox4.Text
End Sub
End Class
So, for example, you could do something like this on your button click event.
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim refNo As Integer = txtRefNo.Text ' Change DataType and TextBox name as appropriate
Dim firstName as String = txtFName.Text
' Repeat setting variables for each field in the row that you're updating
For Each dgr As DataGridViewRow in DataGridView1.Rows
If dgr.Item("RefNo") = refNo Then
dgr.Cells(0).Value = firstName 'Instead of using (0) you can use the column name
dgr.Cells(1).Value = newVar
End If
Next
' Commit the changes/refresh here
End Sub
I don't have the IDE to hand to test this but any problems let me know, I'll have a look into it.

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub