Please have a look to the following code and tell me why it does not move to the next record? I load data programmatically and fill tables in dataset. I could do this by wizard but I want to do it with my own code; because using wizard sometimes does not help understanding the real code behind it.
Private Sub frmSystemOptions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dsOptions = New DataSet
loadOptions()
bsInstitute = New BindingSource(dsOptions, "institute")
bnInstitute = New BindingNavigator(bsInstitute)
InstIdTextBox.DataBindings.Add("Text", dsOptions.Tables("institute"),"instId")
CodeTextBox.DataBindings.Add("Text", dsOptions.Tables("institute"), "code")
NameTextBox.DataBindings.Add("Text", dsOptions.Tables("institute"), "name")
TypeTextBox.DataBindings.Add("Text", dsOptions.Tables("institute"), "type")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Sub loadOptions()
Dim sql As String
Try
sqlConn = New SqlConnection(connString)
sqlConn.Open()
sql = "select * from institute"
daAdapter = New SqlDataAdapter(sql, sqlConn)
daAdapter.Fill(dsOptions, "institute")
'----------------------------------------------------------------------
sqlConn.Close()
Catch ex As Exception
sqlConn.Close()
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
If bsInstitute.Position + 1 < bsInstitute.Count Then
bsInstitute.MoveNext()
Else
bsInstitute.MoveFirst()
End If
Me.Validate()
End Sub
I found the solution. The databounds should be as the following:
InstIdTextBox.DataBindings.Add("Text", bsInstitute, "instId") CodeTextBox.DataBindings.Add("Text", bsInstitute, "code") NameTextBox.DataBindings.Add("Text", bsInstitute, "name") TypeTextBox.DataBindings.Add("Text", bsInstitute, "type")
dataset instead of bsInstitute. But now its perfect. Try
dsOptions = New DataSet
loadOptions()
bsInstitute = New BindingSource(dsOptions, "institute")
InstIdTextBox.DataBindings.Add("Text", bsInstitute, "instId")
CodeTextBox.DataBindings.Add("Text", bsInstitute, "code")
NameTextBox.DataBindings.Add("Text", bsInstitute, "name")
TypeTextBox.DataBindings.Add("Text", bsInstitute, "type")
Catch ex As Exception
MsgBox(Err.Description)
End Try
I was using the dataset for the binding like this
InstIdTextBox.DataBindings.Add("Text", dsOptions.Tables("institute"),"instId")
But whats right I should replace the dsOptions.tables("institute") in the above line of code with the bindingSource I creadted like the following
InstIdTextBox.DataBindings.Add("Text", bsInstitute, "instId")
This way I could use the bindingSource object to navigate records in my dataset.
Related
I want when filtering rows in the textbox then the database is updated from other applications then I do a refresh I want the datagridview that I filter in the textbox in a fixed position and also when selected in the combobox as well. Maybe my code isn't perfect. So there may be the best solution.
Thanks
VIEW DATAGRIDVIEW
Public Class Form1
Dim Path As String = Application.StartupPath()
Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private WithEvents dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PopulateComboBox()
Me.PopulateDataGridView()
Me.clearfiltercombobox()
End Sub
Private Sub PopulateDataGridView()
Try
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0 AND BRAND = #BRAND"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#BRAND", ComboBox1.SelectedValue)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
CType(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = String.Format("ITM LIKE '%{0}%' OR ITM LIKE '%{0}%'", TextBox1.Text)
Catch ex As Exception
MsgBox("No match found")
End Try
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
Me.TextBox1.Text = ""
Me.PopulateDataGridView()
End Sub
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT BRAND FROM EXAMPLE WHERE QTY > 0"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource.
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "BRAND"
ComboBox1.ValueMember = "BRAND"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub clearfiltercombobox()
Try
ComboBox1.ResetText()
TextBox1.Text = ""
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub Refreshonly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refreshonly.Click
Me.clearfiltercombobox()
DataGridView1.Refresh()
End Sub
Private Sub clearall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clearall.Click
Me.clearfiltercombobox()
End Sub
End Class
I am using the following code. While run the combo box displays System.Data.DataRowView rather than the Item name from Database
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim fillcon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\tcs.accdb")
Dim asql As String = ("SELECT ItemName FROM Items ORDER BY ItemName")
Dim da As New OleDbDataAdapter(asql, fillcon)
Dim ds As New DataSet
da.Fill(ds)
ComboBox1.ValueMember = "ItemName"
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
You need to specify the .DisplayMember to one of your fields that you are querying.
I have this class called "SQLControl".
And I have a sub and function like this :
Public Function ConnectionTest() As Boolean
Try
SQLConn.Open()
SQLConn.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub LoadTable(LoadTableQuery As String) 'LoadTableQuery itu variable yang ada didalam si Sub LoadTable
Try
SQLConn.Open()
SQLCmd = New SqlCommand(LoadTableQuery, SQLConn) 'Pemakaian LoadTableQuery
'Load SQL record untuk datagrid
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDataset = New DataSet
SQLDA.Fill(SQLDataset)
SQLConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLConn.State = ConnectionState.Open Then
SQLConn.Close()
End If
End Try
End Sub
Then i use my sub an function to this one :
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles pbAdd.Click
Me.Hide()
MenuTambah.cbLokasiPeminjaman.SelectedIndex = 0
MenuTambah.Show()
If SQL.ConnectionTest = True Then
SQL.LoadTable("SELECT * FROM Tabel_Pinjam")
MenuTambah.DGVTambah.DataSource = SQL.SQLDataset.Tables(0)
Else
MsgBox("Koneksi ke database gagal !")
End If
End Sub
then I want to show the Datagridview called "DGVTambah" in "MenuTambah" Form dataset to my crystalreport, this code is in my "MenuTambah" Form :
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Dim myReport As New ReportDocument
myReport.Load(Application.StartupPath & "\Laporan.rpt")
myReport.SetDataSource(DGVTambah.DataSource)
LaporanViewer.CrystalReportViewer1.ReportSource = myReport
End Sub
But it said "The report has no tables", why I am get this error?
If no table, my datagridview called "DGVTambah" will not show any table, and my query works fine.
Thanks:)
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
I have a DataGridView that is popoulated with the code below; Please note that the codes only contain the important part for brevity. The gridview populates well but the update code is what i need help on.
Dim da As OleDbDataAdapter
Dim ds As DataSet
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Try
'open database
conn.Open()
'get query data
Dim cmd As OleDbCommand = New OleDbCommand(
"SELECT student_name.matric_no,student_name.sname, student_name.fname," &
"result_sheet.course_title,result_sheet.test_score,result_sheet.exam_score,result_sheet.total_score" &
" FROM student_name INNER JOIN result_sheet ON student_name.matric_no = result_sheet.matric_no ", conn)
da = New OleDbDataAdapter(cmd)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
ds = New DataSet()
da.Fill(ds)
da.Dispose()
Dim usertable As DataTable = ds.Tables(0)
'datasource of the datagrid
Dview1.DataSource = usertable
'change the data grid column name
Dview1.Columns(0).HeaderText = "MATRIC NUMBER"
Dview1.Columns(1).HeaderText = "SURNAME"
Dview1.Columns(2).HeaderText = "FIRST NAME"
conn.Close()
Catch ex As Exception
'display message
MsgBox(ex.ToString)
End Try
End Sub
My code to update the GridView is below;
Private Sub update_btn_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles update_btn.Click
Try
da.Update(ds.Tables(0))
Catch ex As Exception
'display message
MsgBox(ex.ToString)
End Try
End Sub
The error I am getting when I click on the Update button is: The DataAdapter.SelectCommand property needs to be initialized.
Please, how do I solve this?