Indicate combobox values with a specific ids? - vb.net

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

Related

vb.net CheckedListbox get value from database

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

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.

SQL Column to TextBox (from ComboBox)

I have managed to add data into a ComboBox from a column out of my SQL table, but I need the rows from across to display in the rest of the textboxes. (I hope I have worded this correctly).
Here is my code currently:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
The above works with no issues, all of the items add into the ComboBox but I need the corresponding rows from the other two columns which are EMAIL_ADDRESS and DEPARTMENT to add into TextBoxes from what is selected in the ComboBox.
Under the SelectedIndex_Changed event of the ComboBox; Enter the following code.
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
End Sub
You Will need to declare the data table dt outside your form's load event so it can be visible to the SelectedIndex_Changed event of the combo box.
I suggest you to use BindingSource to get it done.
Try this:
1- Declare your variable type of BindingSource with events. Also, declare your dataset will be used for data.
Dim WithEvents BS As New BindingSource
Dim ds As New DataSet
2- In your Form Load Event, query your data and bind it with both Binding Source and your ComboBox control.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(ds, "myPopulatedTable")
ComboBox1.DisplayMember = "id"
ComboBox1.DataSource = ds.Tables("myPopulatedTable")
'Here the new code'
BS.DataSource = ds
BS.DataMember = "myPopulatedTable"
End Sub
3- Add a Sub Procedure to display your data into other text boxes controls.
Private Sub DISPLAYRECORD(Optional ByVal table As String = "myPopulatedTable")
TextBox1.Text = ds.Tables(table).Rows(Me.BS.Position)("column1").ToString
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column2").ToString()
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column3").ToString()
End Sub
4- In the PositionChanged event of your Binding Source, call that sub procedure (above)
Private Sub BS_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BS.PositionChanged
DISPLAYRECORD()
End Sub
5- Finally, to sync your data with ComboBox selection, you need to change the position of that Binding Source according to the ComboBox index selection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
BS.Position = ComboBox1.SelectedIndex
End Sub

How to update SQLite database from DataGridView in Visual Basic 2013 .net?

I am displaying data from SQLite table into a DataGridView as following -
Private Sub Subjects_Manager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SQLiteConnection("Data Source = c:\demo\test.db;Version=3;")
con.Open()
sql = "SELECT * FROM med_subjects"
da = New SQLiteDataAdapter(sql, con)
da.Fill(ds, "SubjectsList")
DataGridView1.DataSource = ds.Tables("SubjectsList").DefaultView
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Subject Id"
.Columns(1).HeaderCell.Value = "Subject Name"
End With
DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
con.close()
End Sub
I want to save changes done in DataGridView (either Updation of Row/s or Insertion of Row/s) back to SQLite table. But I couldn't find a way to do so.
Edit 1 :
I know Insert/Update Queries of SQLite, but what I don't know is how & where to keep them so that they can be triggered in responses to changes made in DataGridView. e.g.
' I am using this variable for demonstration, in reality InsertSubjectSqlString will be equal to changes done in DataGridView
Dim InsertSubjectSqlString As String = "Insert into med_subjects (Subject_Name) Values ('_Miscellaneous')"
Dim SqliteInsertRow As SQLiteCommand
SqliteInsertRow = con.CreateCommand
SqliteInsertRow.CommandText = InsertSubjectSqlString
SqliteInsertRow.ExecuteNonQuery()
But I don't know, where should I put it?
Edit 2:
After seeing comments and answers, I came to know that there is No direct way to Insert/Update Sqlite database from DataGridView. So I was curious, if there is any event like RowSelected which would
trigger on selecting a row and get that row's data
then taking the row's data into multiple text boxes and lastly
triggering Insert/Update queries taking values from these textboxes
by a button
I know it's highly hypothetical with NO sample codes, but it's because I am asking for Event name.
Call this on LeaveRow event or CellEndEdit
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
Dim i as integer
Try
for i = 0 to datagrid.rows.count-1
myUpdate(datagrid.item(0,i).tostring() , datagrid.item(1,i).tostring())
next
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
note , you can also give the column name of your grid in place of column index , like this datagrid.item("fname",i).tostring()
Here we will save in database:
Sub myUpdate(byval fname as string , byval lname as string)
Try
dim con as new sqlconnection("you connection string")
dim cmd as new sqlcommand
con.open()
cmd.connection= con
cmd.commandtext="insert into table (fname,lname) values (#fname,#lname)"
cmd.Parameters.AddWithValue("#fname", fname)
cmd.Parameters.AddWithValue("#lname", lname)
cmd.ExecuteNonQuery()
Con.close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End sub
I hope this will help you to solve !
There are many ways to manipulate data .
CristiC
I dont think you will find some magic way that the DataGridView and DataTable are going to persist things automatically to the backend SQLite database. As you are hinting at I think you will have to rely on events.
I think the event you are missing is answered here stackoverflow cell value changed event
Ok I think is better to use CellEndEdit, because LeaveRow is triggered only if you click on other row.
Look on this example.
you must use: da.Update(ds.Tables("SubjectsList").DefaultView)
Imports System.Data.SqlClient
Public Class Form1
Const connectionstring As String = "server=(local);database=TestDB;uid=sa;pwd=sa;"
Private SQL As String = "select * from customer"
Private con As New SqlConnection(connectionstring)
Private dt As New DataTable
Private adapter As New SqlDataAdapter(SQL, con)
Private commandbuilder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
adapter.Update(dt)
End Sub
End Class
Please use this code hopefully it will work
Imports System.Data.SQLite
Public Class Form
Dim con As New SQLite.SQLiteConnection
Dim da As New SQLite.SQLiteDataAdapter
Dim dt As New DataTable
Dim cmdbl As New SQLite.SQLiteCommandBuilder
Dim dlgResult As DialogResult
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
dlgResult = MessageBox.Show("Do you want to save the changes you made?", "Confirmation!", MessageBoxButtons.YesNo)
If dlgResult = DialogResult.Yes Then
Try
con.Open()
cmdbl = New SQLiteCommandBuilder(da)
da.Update(dt)
MsgBox("Updated successfully!")
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
End Class

SqlDataAdapter missing DeleteCommand

I am loading a VB.NET DataGridView using an SqlDataAdapter to fill a DataSet and then setting the DataSource of the DataGridView to the DataSet.
For some reason, the only command that is populated with the SqlCommandBuilder is the SelectCommand. I realize I am only specifying a SELECT query, but I thought the purpose of the SqlCommandBuilder is to generate the Update/Delete/Insert command for me.
The following is the applicable code:
Dim _dstErrorLog As New DataSet
Dim _adapter As SqlDataAdapter
Dim _builder As SqlCommandBuilder
Private Sub ErrorLog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call LoadErrorLog()
End Sub
Private Sub LoadErrorLog()
Dim strSql As String
strSql = "SELECT Ident, LogDate, LogDesc FROM dbo.ErrorLog ORDER BY DescDateTime DESC"
_adapter = New SqlDataAdapter(strSql, dataLayer.Connection)
_builder = New SqlCommandBuilder(_adapter)
_adapter.Fill(_dstErrorLog)
grdErrorLog.DataSource = _dstErrorLog.Tables(0)
End Sub
Private Sub grdErrorLog_UserDeletingRow(sender As Object, e As DataGridViewRowCancelEventArgs) Handles grdErrorLog.UserDeletingRow
_adapter.Update(_dstErrorLog.Tables(0))
End Sub
When I delete a row, it disappears from the DataGridView but when I re-open the form, the data is all still there. Do I need to specify the DeleteCommand myself? And if so, then what is the purpose of the SqlCommandBuilder??
Use the UserDeletedRow event, not the UserDeletingRow.
In the UserDeletingRow event the changes made to your DataGridView are still not committed to the DataSource binded, so calling the SqlDataAdapter.Update in that event doesn't result in any changes to the database because the table is still unchanged.
Private Sub grdErrorLog_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles grdErrorLog.UserDeletingRow
Dim count = _adapter.Update(_dstErrorLog.Tables(0))
Console.WriteLine("Rows deleted:" & Count)
End Sub
Infact in the UserDeletingRow the argument e is a DataGridViewRowCancelEventArgs meaning that you could still cancel the deletion setting e.Cancel = True