Update DataGridView with dataview - database

I have a VB.NET 2010 application that loads data from SQL Server to a datagridview through adapter.fill(). When I update the database it works fine but my problem is that when i use the dataview to filter the data based on combobox selection the method adapter.update(table) does not work!
Is there away to do it with the filter applied?
Private Sub cmbDepartment_SelectedIndexChanged(...)
Handles cmbDepartment.SelectedIndexChanged
Dim filter As String
Try
lblDepartmentId.Text = ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0)
filter = "dprtId = " & lblDepartmentId.Text
dvSection = New DataView(ds.Tables("section"), filter, "", DataViewRowState.CurrentRows)
table = dvSection.ToTable
dgvSections.DataSource = table
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnSaveDepartment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSaveDepartment.Click
Dim cbDep As SqlCommandBuilder
Dim numRows As Integer
Try cbDep = New SqlCommandBuilder(daDep)
Me.Validate() numRows = daDep.Update(ds.Tables("section"))
MsgBox(numRows & " Rows affected.")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub

The way you are currently doing your filtering is by creating a new DataTable and binding this to your DataGridView data source. This breaks the association between the original DataSet and that table so when you call Update your changes are not recovered.
Try changing to something like the code below instead (I've left out the try catch blocks, they don't change the idea that fixes your problem).
When you first set the data source to the grid set it to a form level private dvSection field:
Public Class Form1
' Here we declare some class level variables.
'These are visible to all members of the class
Dim dvSection As DataView
Dim tableAdapter As New DataSet1TableAdapters.CustomersTableAdapter()
Dim ds As New DataSet1()
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' We fill our dataset - in this case using a table adapter
tableAdapter.Fill(ds.Customers)
dvSection = ds.Customers.DefaultView
DataGridView1.DataSource = dvSection
End Sub
' Here is the code to filter.
' Note how I refer to the class level variable dvSection
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim filter As String
lblDepartmentId.Text = ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0)
filter = "dprtId = " & lblDepartmentId.Text
dvSection.RowFilter = filter
dvSection.RowFilter = filter
End Sub
' And here is the update code referring to the class level table adapter
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
tableAdapter.Update(ds.Customers)
End Sub
End Class
One other approach that might make things easier is to introduce a binding source and set the filter on that. Either was should work fine however.

Related

How do I display access database in VB?

So I have been able to connect my database to VB forms, and I am also able to see the table and the fields within. But I can't figure how to make the data appear in the table because it's just blank.
I do have some data stores in the actual access database but it won't show up in my program.
Is there a particular code I need to write? This is what I have so far. The database is called the 'POS system'.
Private Sub OrdersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles OrdersBindingNavigatorSaveItem.Click
Me.Validate()
Me.OrdersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.POS_systemDataSet)
End Sub
It is usually a good idea to separate your database code from your user interface code. Create a connection and a command in a Using block so they will be closed and disposed at End Using. Pass the connection string to the constructor of the connection. Pass the CommandText and connection to the constructor of the command. Open the connection and execute the command returning a DataReader to load the DataTable.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetData()
DataGridView1.DataSource = dt
End Sub
Private Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Select * From SomeTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function

Autocomplete TextBox Column in DataGridView Stopped working

I have a datagridview with one of its column as TextBox. I wrote a function to populate values from database and suggest values to autocomplete the text. I achieved it, and then I started coding to make a column auto increment (Sr.No) , so I wrote some more lines of code and changed some properties and all of a sudden the textbox stopped auto-completing. Now I tried every possible step to make it work but failed. I dont know what is the property that I changed affected this.
I am putting my code here, please help
This is the code for Editingcontrolshowing event...
Private Sub DataGridView2_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
DataGridView2.BeginEdit(True)
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteCustomSource = AutoCompleteLoad()
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
End If
End Sub
This is the autocomplete function where I loaded values...
Public Function AutoCompleteLoad() As AutoCompleteStringCollection
Dim str As AutoCompleteStringCollection = New AutoCompleteStringCollection()
Dim ConnectionString As SqlConnection = New SqlConnection("data source=ADMIN-PC\SQLEXPRESS; database=billdev;Trusted_Connection=yes;")
Dim strSQL As String = "SELECT * from bill;"
Dim SQLcommand As New SqlCommand(strSQL, ConnectionString)
ConnectionString.Open()
Dim reader As SqlDataReader
reader = SQLcommand.ExecuteReader()
While reader.Read()
str.Add(reader.Item(1))
End While
Return str
End Function
This is the extra code I added before it stopped working, but I think this doesn't make any difference
Private Sub DataGridView2_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView2.RowPrePaint
If e.RowIndex >= 0 Then
Me.DataGridView2.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
End If
End Sub
I found the solution.
I tried changing every property of the datagridview randomly. And finally got to the point.
It is the WRAP property of the column itself.

VB.NET SQL Search from table

I've created the table: "tblInterni" on my sql database and made so that I can see it on a datagridview.
I am now making a search function so that if I search for a name it loads everyone with that name in the datagridview, but the query I made isn't working.
Private Sub Home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=dbTest;User ID=pwdDb;Password=pwdDb")
Dim adapter As New SqlDataAdapter("SELECT * FROM tblInterni", conn)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim searchQuery As String = "SELECT * From tblInterni WHERE name like '%" & TextBox1.Text & "%'"
End Sub
form graphic
Given that you are retrieving all the data when the form loads, what you should be doing is binding your DataTable to the DataGridView via a BindingSource and then filtering that data by setting the Filter property of the BindingSource.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Dim table As New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Using
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
BindingSource1.Filter = $"MyColumn LIKE '%{TextBox1.Text}%'"
End Sub
Note that the BindingSource would be added in the designer, just like the grid.
This is still not ideal though. If the user wants to type several characters in order to filter then this code will modify the filter several times unnecessarily and actually slow them down. A better idea is to use a Timer to add a small delay before filtering that resets each time they make a change. That way, if they type several characters quickly enough, the filter will only change after the last character.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Dim table As New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Using
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'Start/reset the filter timer.
Timer1.Stop()
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BindingSource1.Filter = $"MyColumn LIKE '%{TextBox1.Text}%'"
End Sub
You can experiment a bit with the Interval of the Timer but you should find that something around 300 milliseconds should mean that filtering still feels fast enough but typing at a reasonable speed should avoid most unnecessary intermediate filters.

Linq-to-SQL SubmitChanges not updating physical database

I am new here and only signed up because I desperately need the solution to my problem. I have a VB.NET project that is using a local .MDF file that I have imported into my project. The primary keys are intact so I know that isn't my issue.
I am using Linq-to-SQL to query the database and make changes. On my main form I use a Data Grid View that is populated by a query. I am having an issue with my insert where the query works fine and the DGV gets updated with newly created data, but when I call SubmitChanges() the changes do not get saved to the actual physical database. I am not sure what I am missing or doing wrong.
Here is my code to better assist your educated answer.
Public Class frmCell_Leader
'Reference DataContext
Private db As New MarquardtClassesDataContext()
Private Sub frmCell_Leader_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FillProductionGrid()
PrepareInsertFields()
End Sub
Private Sub FillProductionGrid()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Populate DGV
Dim query = From marq In db.tblProductivities
Select
marq.PartNum, marq.Produced, marq.Packed, marq.Issue, marq.StationNum, _
marq.PlanDownTime, marq.UnplannedDownTime, marq.CurDate
dgvProduction.DataSource = query
End Sub
Private Sub PrepareInsertFields()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Fill Planned Downtime Combo Box
Dim PlannedQuery = From planned In db.tblPlannedDownTimes
Select planned.Plan_ID, planned.Description, planned.Active
Where Active = True
cboPlanned.DataSource = PlannedQuery
cboPlanned.DisplayMember = "Description"
cboPlanned.ValueMember = "Plan_ID"
'Fill UnPlanned Downtime Combo Box
Dim UnPlannedQuery = From unplanned In db.tblUnplannedDownTimes
Select unplanned.Unplan_ID, unplanned.Description, unplanned.Active
Where Active = True
cboUnplanned.DataSource = UnPlannedQuery
cboUnplanned.DisplayMember = "Description"
cboUnplanned.ValueMember = "UnPlan_ID"
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
'Add the new Production to database
'Create an productivity object
Dim marqpro As New tblProductivity With {
.PartNum = CShort(txtPartNumber.Text),
.Produced = CShort(txtProduced.Text),
.Packed = CShort(txtPacked.Text),
.Issue = txtIssue.Text,
.PlanDownTime = CShort(cboPlanned.SelectedValue),
.UnplannedDownTime = CShort(cboUnplanned.SelectedValue),
.CurDate = Date.Today}
'insert newly created data
Try
'Submit changes too database
db.tblProductivities.InsertOnSubmit(marqpro)
db.SubmitChanges()
db.Refresh(Data.Linq.RefreshMode.KeepCurrentValues, marqpro)
'Refresh DGV
FillProductionGrid()
MessageBox.Show("Data added successfully")
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
End Sub
End Class
Perhaps you have an .mdf file in your project that is getting copied to the bin/debug folder everytime you build.
Why isn't my SubmitChanges() working in LINQ-to-SQL?

Unable to display SQL database data on Visual basic form

I am facing a problem displaying the records of my table on the visual basic form I have created.
This is my code :
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myconnection = New SqlConnection("server=HOME-PC\SQLEXPRESS;uid=sa;pwd=123;database=college")
myconnection.Open()
mycommand = New SqlCommand("SELECT * from demo3)", myconnection)
Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
Dim mydsStudent As New DataSet()
mySqlDataAdapter.Fill(mydsStudent, "Student")
ra = mycommand.ExecuteNonQuery()
MessageBox.Show("Data Displayed" & ra)
myconnection.Close()
End Sub
End Class
Note: my database name is "college" , table name is "demo3" . Table contains 2 columns namely name and roll no. How to display the data in those columns on the visual basic form that I have created ?
You don't need to call execute non query. You can bind the dataset to a DataGridView. Like this
Dim DataGridView1 as new DataGridView()
DataGridView1.DataSource = mydsStudent
'Your table goes here, not sure about the exact propety name, hope it works.
DataGridView1.DisplayMember = "demo3"
Me.Controls.Add(DataGridView1)

Resources