Vb.net Editing DatagridView - vb.net

I created a simple program where I can search through a database table. Add data and remove data through a button. Now I want to be able to update the data within the datagrid view however i am getting the classic error: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I have the primary key in the data grid that is not attached to anything in the vb.net program nor in the database at this time. I am not sure what I am missing.
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
adap.InsertCommand = builder.GetInsertCommand()
' adap.UpdateCommand = builder.GetUpdateCommand()
adap.UpdateCommand = builder.GetUpdateCommand
adap.Fill(dt)
InventoryDetailsBindingSource.DataSource = dt
DataGridView1.DataSource = InventoryDetailsBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = String.Format("First_Name Like '%{0}%'", TextBox1.Text)
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
adap.Update(dt)
DataGridView1.[ReadOnly] = True
Button2.Enabled = False
End Sub
End Class

Actually I was incorrect. I did not have a primary key set on my database. I dropped my table - recreated with primary key.

Related

Combo Box Declaration expected

When I got the value for the combo box from the MySQL database it seems getting error declaration expected in line 4. Can anyone help me? Here I attach my code
Imports MySql.Data.MySqlClient
Public Class Utama
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Me.Hide()
Dim utama As New Login
utama.Show()
End Sub
Private Sub KeluarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KeluarToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub SupplierToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SupplierToolStripMenuItem.Click
Me.Hide()
Dim supplier As New Supplier
supplier.Show()
End Sub
Private Sub ProdukToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ProdukToolStripMenuItem.Click
Me.Hide()
Dim Produk As New Produk
Produk.Show()
End Sub
Private Sub CetakToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CetakToolStripMenuItem.Click
Me.Hide()
Dim Cetak As New Cetak
Cetak.Show()
End Sub
Dim connection As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Dim da As New MySqlDataAdapter("select * from supplier", connection)
Dim dt As DataTable
da.fill(dt)
ComboBox1.Datasource=dt
ComboBox1.DisplayMember = "npwp"
ComboBox1.ValueMember = "npwp"
End Class
You need to put that code inside a method. You can't just put arbitrary code anywhere in a class. The only thing that can be directly in the class is a declaration. The first three lines are declarations, so they're OK. The last four lines are not. That code should be inside a method somewhere. If you want to execute that code when the form loads then it should be in the Load event handler. This is pretty elementary stuff that any beginners tutorial would cover, so maybe you should work your way through such a tutorial.
First, create a method as shown below and check the exception.
Private Sub Utama_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim connection As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Dim da As New MySqlDataAdapter("select * from supplier", connection)
Dim dt As new DataTable
da.fill(dt)
ComboBox1.Datasource = dt
ComboBox1.DisplayMember = "npwp"
ComboBox1.ValueMember = "npwp"
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Save row colour after closing form

I got this for saving all data when closing the form.
Public Class Form1
Dim table As New DataTable("Table")
ReadOnly p As String = Path.Combine("C:\test.xml")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
If Not File.Exists(p) Then
table.Columns.Add("Company", Type.GetType("System.String"))
table.Columns.Add("Date", Type.GetType("System.DateTime"))
table.Columns.Add("Code", Type.GetType("System.String"))
table.Columns.Add("Position", Type.GetType("System.String"))
table.Columns.Add("Note", Type.GetType("System.String"))
table.Columns.Add("Solved", Type.GetType("System.DateTime"))
Else
table.ReadXml(p)
End If
DataGridView1.DataSource = table
End Sub
I was using this for mark solved row:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.CurrentRow.Cells("Solved").Value = DateTime.Now
DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
And this for "repair solved row" button:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.White
DataGridView1.CurrentRow.Cells("Solved").Value = ""
DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
The problem is, that my saving doesn't save this coloured row, it's white when I open the form again.
Any idea? I'm really new to this.
Thanks.
The following code should color the rows as described in my comments.
Private Sub ColorRows()
For Each row As DataGridViewRow In DataGridView1.Rows
If (Not row.IsNewRow) And (row.Cells("Solved").Value IsNot DBNull.Value) Then
row.DefaultCellStyle.BackColor = Color.PaleGreen
End If
Next
End Sub
You could call this code in the forms Load event right after the data has been loaded into the grid. Something like…
….
DataGridView1.DataSource = table
ColorRows()
Edit...
After some testing, it appears that when the code is setting the "Solved" value to an empty string, in the Button4_Click event with...
DataGridView1.CurrentRow.Cells("Solved").Value = ""
This is setting a default min Date value as you noted in the xml file.
Change this line of code to...
DataGridView1.CurrentRow.Cells("Solved").Value = DBNull.Value
It should work as expected then.
Below is the complete code I used to test this.
Dim table As New DataTable("Table")
ReadOnly p As String = Path.Combine("D:\Test\XML\_test_100.xml")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
If Not File.Exists(p) Then
table.Columns.Add("Company", Type.GetType("System.String"))
table.Columns.Add("Date", Type.GetType("System.DateTime"))
table.Columns.Add("Code", Type.GetType("System.String"))
table.Columns.Add("Position", Type.GetType("System.String"))
table.Columns.Add("Note", Type.GetType("System.String"))
table.Columns.Add("Solved", Type.GetType("System.DateTime"))
Else
table.ReadXml(p)
End If
DataGridView1.DataSource = table
ColorRows()
End Sub
Private Sub ColorRows()
For Each row As DataGridViewRow In DataGridView1.Rows
If (Not row.IsNewRow) And (row.Cells("Solved").Value IsNot DBNull.Value) Then
row.DefaultCellStyle.BackColor = Color.PaleGreen
End If
Next
End Sub
Private Sub btnWriteToXML_Click(sender As Object, e As EventArgs) Handles btnWriteToXML.Click
table.WriteXml(p, XmlWriteMode.WriteSchema)
End Sub
Private Sub btnSolved_Click(sender As Object, e As EventArgs) Handles btnSolved.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.CurrentRow.Cells("Solved").Value = DateTime.Now
'DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub
Private Sub btnRepairSolved_Click(sender As Object, e As EventArgs) Handles btnRepairedSolved.Click
DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.White
DataGridView1.CurrentRow.Cells("Solved").Value = DBNull.Value
'DataGridView1.DataSource = table
DataGridView1.ClearSelection()
End Sub

How to update an Access DB from a DataGridView in Visual Basic

I am creating an inventory application which runs off of an Access DB in visual studio, using visual basic. I can populate my data grid view just fine, but when I try to add new information into the data grid view, it does not number correctly and it does not append my database.
I have tried binding and updating using the table adapter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Here is my code:
Public Class Form1
Private Sub enterbtn_Click(sender As Object, e As EventArgs) Handles enterbtn.Click
If username.Text = "Tanner" And password.Text = "bmis365" Then
GroupBox1.Visible = False
Else
MsgBox("Incorrect Username or Password, please try again.")
username.Clear()
password.Clear()
username.Focus()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.CurrentCell = Nothing
'This line of code loads data into the 'Database1DataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is where my new info is to be appended into the database, once the button is clicked.
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
'The Following Code is from https://social.msdn.microsoft.com/Forums/vstudio/en-US/36c54726-4f49-4e15-9597-7b201ec13ae7/search-in-datagrid-using-textbox-vbnet-without-data-connectivity?forum=vbgeneral
For Each row As DataGridViewRow In DataGridView2.Rows
For Each cell As DataGridViewCell In row.Cells
If Not IsNothing(cell.Value) Then
If cell.Value.ToString.StartsWith(searchbar.Text, StringComparison.InvariantCultureIgnoreCase) Then
cell.Selected = True
DataGridView2.CurrentCell = DataGridView2.SelectedCells(0)
End If
End If
Next
Next
End Sub
End Class
My output initially has 3 rows(numbered 1, 2, and 3) but any that are added through the application have the numbers -1, -2, -3 and so on. Also, when I close the program and restart it, my original rows (1, 2, and 3) are still there from when I entered them in the DB file, but any that were added through my application are gone.
Here is one way to do an Update, as well as a few other common SQL manipulations/operations.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

Vb.net hyperlink Dataview and listing between price range

I am working on a assignment in which I have to use VB.net and Access database in order to make a bookstore. One of the requirements is that I have to make a table with book titles and customer names with a hyperlink on the title and customer name which will redirect them to a new page. I have the table working, but I am not able to add a hyperlink to one of the columns in the table. Also there is a searching feature where I have to print all the books between a price range (ex. $20 < price <= $30) I have the radio buttons setup but I am not able to do the actual searching and get good values. My code is below:
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class CustomerSearching
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RadioButton1.Visible = False
RadioButton2.Visible = False
RadioButton3.Visible = False
RadioButton4.Visible = False
RadioButton5.Visible = False
End Sub
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=" + Server.MapPath("~/bookstore.accdb"))
conn.Open()
End Sub
Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Response.Redirect("Customer.aspx")
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + Server.MapPath("~/bookstore.accdb"))
RadioButton1.Visible = True
RadioButton2.Visible = True
RadioButton3.Visible = True
RadioButton4.Visible = True
RadioButton5.Visible = True
If (RadioButton1.Checked) Then
conn.Open()
Dim sql As String = "SELECT * FROM books WHERE price < $10.00"
Dim dbcomm As New OleDb.OleDbCommand(sql, conn)
Dim dbread = dbcomm.ExecuteReader()
bookSearching.DataSource = dbread
bookSearching.DataBind()
dbread.Close()
conn.Close()
End If
End Sub
Protected Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
For the hyperlink I used the vb option to design and dragged a sqlDataSource and a gridview and linked the two together with my bookstore.accdb file. You're help is much appreciated. Thanks a lot.

open selected row in datagridview to edit in Another form

I am using vb.net designer to connect to access database .
On my Form1 I have a DataGridView And Two Button For Add And Edit
I Make Form2 To Add Data Into Database And Worked OK ..
Imake Form3 Wiht Same form2 Content
Now I need When i selcet row in DataGridView And Clic Edit Button The data of selected row show on form3 for Edit it
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.SalesTableAdapter.Fill(Me.OrdersDataSet.sales)
Me.DateTimePicker1.Value = Date.Today
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
SalesBindingSource.Filter = String.Format("date = '{0}'", DateTimePicker1.Value.ToShortDateString())
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.Show()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Form3.Show()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub SalesDataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles SalesDataGridView.CellContentClick
End Sub
End Class
You need to approach this in a modal/dialog way. You only need one form for both add and edit.
Add/Edit form
Add a parameterized constructor to the form.
Public Sub New(row As DataRowView)
Me.InitializeComponent()
'Me.ctlAge: NumericUpDown control.
'Me.ctlBirthday: DateTimePicker control.
'Me.ctlName: TextBox control.
If (row Is Nothing) Then
'Add mode, set default values:
Me.ctlAge.Value = 0
Me.ctlBirthday.Value = Date.Now
Me.ctlName.Text = String.Empty
Else
'Edit mode, set current values:
Me.ctlAge.Value = CDec(row.Item("AGE"))
Me.ctlBirthday.Value = CDate(row.Item("BIRTHDAY"))
Me.ctlName.Text = CStr(row.Item("NAME"))
End If
End Sub
You also need an accept button and a cancel button.
Friend Sub btnAcceptClicked(sender As Object, e As EventArgs) Handles btnAccept.Click
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Friend Sub btnCancelClicked(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Main form
Add method:
Private Sub btnAddClicked(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
Using f As New AddOrEditForm(CType(Nothing, DataRowView))
If (f.ShowDialog() = Windows.Forms.DialogResult.OK) Then
Dim view As DataView = TryCast(Me.SalesDataGridView.DataSource, DataView)
If (view Is Nothing) Then
Throw New InvalidCastException()
End If
Dim viewRow As DataRowView = view.AddNew()
viewRow.EndEdit()
viewRow.Item("AGE") = f.ctlAge.Value
viewRow.Item("BIRTHDAY") = f.ctlBirthday.Value
viewRow.Item("NAME") = f.ctlName.Text
viewRow.EndEdit()
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Edit method:
Private Sub btnEditClicked(sender As Object, e As EventArgs) Handles btnEdit.Click
Try
Me.SalesDataGridView.EndEdit()
If (Me.SalesDataGridView.SelectedRows.Count > 0) Then
Dim gridRow As DataGridViewRow = Me.SalesDataGridView.SelectedRows(0)
Dim viewRow As DataRowView = TryCast(gridRow.DataBoundItem, DataRowView)
If (viewRow Is Nothing) Then
Throw New InvalidCastException()
End If
Using f As New AddOrEditForm(viewRow)
If (f.ShowDialog() = Windows.Forms.DialogResult.OK) Then
viewRow.BeginEdit()
Try
viewRow.Item("AGE") = f.ctlAge.Value
viewRow.Item("BIRTHDAY") = f.ctlBirthday.Value
viewRow.Item("NAME") = f.ctlName.Text
viewRow.EndEdit()
Catch ex As Exception
viewRow.CancelEdit()
Throw ex
End Try
End If
End Using
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub