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.
Related
Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class
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
I am trying to add new row of data in the DataGridView that is located in Form4. The data is to be entered in the Form3 into TableAdapter that is bound with DataGridView.
On the Form4 I have a button that opens Form3 and it suppose to add new rows into DatagridView but seems like it is not doing it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Form3.Show()
Form4.DbTableDataGridView.Rows.Add() 'this is not executed?
End Sub
On the Form3 there is a TableAdapter that suppose to fill in new added rows in the DbTableDataGridView and then saves the changes. Something like:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form4.DbTableDataGridView.Rows.Add(Me.DbTableTableAdapter)
End Sub
This works fine.
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form3.ShowDialog()
End Sub
End Class
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form4.DataGridView1.Rows.Add("Add Something here")
End Sub
End Class
Does the data in your datagridview is from database?
You can have a Public Sub in your Form4 to show the records.
Example:
Dim cn As New SqlConnection("your connection string here")
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Public Sub ShowRecord()
cn.Open()
With cmd
.Connection = cn
.CommandText = "Your command text here"
End With
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
dataGridView1.DataSource = dt
cn.Close()
End Sub
In your Form3:
you can save the data in the database then call the sub in form4 like
form4.ShowRecord()
This is just a simple example though
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.
How can I remove item in comboBox after
I choose it and put into listBox.
Here's my code. Please help me.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class frmAdvancePayment
Private Sub frmAdvancePayment_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstBillNum.Items.Clear()
Dim connection_string As String = "Data Source=.\sqlexpress;Initial Catalog=CreditAndCollection;Integrated Security=True"
Dim connection As New SqlConnection(connection_string)
connection.Open()
Dim sql As String = "select BillNum from tblBillingSched where Status ='Unpaid'"
Dim da As New SqlDataAdapter(sql, connection_string)
Dim dt As New DataTable
da.Fill(dt)
cmbBillNum.DataSource = dt
cmbBillNum.DisplayMember = "BillNum"
cmbBillNum.ValueMember = "BillNum"
connection.Close()
End Sub
Private Sub btnGet_Click(sender As Object, e As EventArgs) Handles btnGet.Click
lstBillNum.Items.Add(cmbBillNum.SelectedValue)
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lstBillNum.Items.Clear()
End Sub
End Class
it's what you expect ?
Private Sub ComboBox1_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
Dim index As Integer = ComboBox1.SelectedIndex
ListBox1.Items.Add(ComboBox1.Items(index))
ComboBox1.Items.RemoveAt(index)
End Sub