Visual Basic Connect to Access DataBase - vb.net

I'm new to access database, and the following code shows the general process I learned in class to connect visual basic to access database and display data on form.
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SalesDataConnection As New OleDbConnection("provider=microsoft.ACE.oledb.12.0;data source=AccessClassActivity.accdb")
Dim SalesDataSet As New DataSet()
Dim SalesDataAdapter As New OleDbDataAdapter("Select * from customers", SalesDataConnection)
'SalesDataConnection.Open()
SalesDataAdapter.Fill(SalesDataSet)
SalesDataGridView.DataSource = SalesDataSet.Tables(0).DefaultView() ' defaultView is the datasheet view
SalesDataConnection.Close()
End Sub
End Class
I have a access file named AccessClassActivity. I have a main form named form1, a button named button1, and a datagridview named SalesDataGridView.
I comment out SalesDataConnection.Open() on purpose to see what happens, but nothing happens and everything works well. I'm just wondering why data can be shown without opening data connection to database. Do we really need this method?

Related

Is there a way to input a text from textbox1.text to input box of a website? I'm using a chromium browser in Visual Basic

I'm trying to make a program in which I can input my username from my Visual basic project Textbox1 to facebook input box username. I'm using chromium from CefSharp for webbrowser. I got the id through 'view page source' which is 'email'. but what I'm not sure if my line of code is correct.
Here are my code so far:
Imports CefSharp
Imports CefSharp.Web
Imports CefSharp.JavascriptBinding
Imports CefSharp.Event
Public Class Form2
Private WithEvents browser As ChromiumWebBrowser
Sub New()
InitializeComponent()
InitializeChromium()
End Sub
Private Sub InitializeChromium()
Dim settings As New CefSettings()
CefSharp.Cef.Initialize(settings)
Dim browser As New ChromiumWebBrowser("https://www.facebook.com")
Panel1.Controls.Add(browser)
browser.Dock = DockStyle.Fill
End Sub
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
browser.ExecuteScriptAsync("document.getElementById('email').value='ansdew#gmail.com'")
End Sub
When I run this, I get the error message
Object reference not set to an instance of an object.'
The line of code which this exception
browser.ExecuteScriptAsync("document.getElementById('email').value='ansdew#gmail.com'")
I don't know if the inside of this
ExecuteScriptAsync
is correct and I need to find the correct script so I can input my username/email using my VB project.
Let me know also if I need to include some lines of code.
Thanks!

How to keep the data of a form after hiding it

The user enters data in Form1 for example his name and phone number, he clicks on the "next" button that opens Form2 and Hide Form1, if he clicks on the "back" button I want the program to show Form1 with the data he entered before
The code for the "Next" Button in Form1:
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
Dim MyForm As New Form2
MyForm.Show()
Me.Hide()
End Sub
What should I do in order to keep the data the user entered if he comes back to Form1?
The code for the "Previous" button in Form2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form1.Show()
Me.Close()
End Sub
One approach you could use is to only the use the DEFAULT INSTANCES of your Forms. These are accessed by using only the name of the Form, WITHOUT ever using the "New" keyword.
You're doing exactly that in Form2 when you show Form1 with:
Form1.Show()
This works because Form1 is your startup object and VB.Net used the default instance to start the application.
You could do the same thing in Form1, to show Form2:
' ... code in Form1 ...
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
Form2.Show() ' show the default instance of Form2 (do NOT use the "new" keyword)
Me.Hide()
End Sub
Just make sure in all places you Hide() the current form instead of closing it.
You can access the properties/fields of the default instances using the same syntax to show them, using only their name. For example, here is a made up value being accessed on Form2:
Dim userName As String = Form2.txtAddress1.Text
This assumes that Form2 was previously displayed and populated by the user. You could access the Forms from anywhere in the code using this type of syntax.
If you want to implement your own "default instance" mechanism, you could use Shared members in a class:
Public Class WizardForms
Public Shared F1 As New Form1
Public Shared F2 As New Form2
Public Shared F3 As New Form3
End Class
Then you could use code like this to display one:
WizardForms.F2.Show()
This would work as long as you are only HIDING the forms. If you allow the user to close the Forms (or close them via code), then you'd need extra code to make sure they get recreated as needed.

VB Adding an item to listbox on a different form giving null reference exception

I am getting a an Null reference exception when trying to add an item to a listbox in a different form.
This is my error at run time.
An unhandled exception of type 'System.NullReferenceException'
occurred in ... Additional information: Object reference not set to an
instance of an object.
I am trying to connect the Mainform by initializing it at the top of the class of the secondForm. after I have my data i want to add it to a listbox it the mainform.
Public Class FormHairdresser //The second form
Dim varMainForm As FormMain //connecting the forms ?
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
hairdresser = HairdresserChoices(HairdresserID) // get the data
varMainForm.lstListBox.Items.Add(hairdresser) //Run time error breaks here.
All i had to to was write the form name instead of ininalised variable.
FormMain.lstListbox.Items.Add("item")
Instead of
Dim varMainForm As FormMain
varMainForm.ListBox.Items.Add("item")
You cannot simply create a new instance of your main form (as has been suggested and expect that to work, you need an actual reference to the mainform that you have created. To help you see the logic involved;
Create a new Winforms project. In the default Form1 add a textbox and a button.
Now add a new form to this application (you can leave it with its default name of Form2. To this form add a TextBox (call it myTextBox) and a button.
Now go back to your first form and doubleclick the button to access the click handler in code. Add the following:
Dim frm as New Form2
frm.Show
Press f5 and click the button and you'll see a new form 2. So far so good.
Now open up the code for Form2 and add the following code so that it ends up looking like this:
Public Class Form2
Private frm As Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frm.TextBox1.Text = myTextBox.text
End Sub
End Class
build, press f5 and click the button on form1, in the new form2 enter some text in the text box and click the button, you get your null reference exception. The reason you get this is because at the moment the private field frm inForm2 refers to Nothing.
Now open up the code in Form2 and add a constructor and the following code so that it ends up looking like this:
Public Class Form2
Private frm As Form1
Public Sub New(byval frm1 As Form1)
'first we should make sure that we have a parameter to play with
If Not IsNothing(frm1) Then
frm = DirectCast(frm1,Form1)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frm.TextBox1.Text = myTextBox.text
End Sub
End Class
Finally go back to your first forms buttonclick handler and change the code slightly so that it looks like this;
Dim frm as New Form2(Me)
frm.Show
Build and run your application, now when you enter text into the textbox in form2 and click the button it will appear in the textbox in Form1.
The reason why this happens is because you have passed an actual reference to the form1 that was originally created when the application started to form2. By casting that reference to your private field used to represent form1 in form2 you can then use it to properly refer to things on form1. This is a very simple concept but one which you need to learn before you will make progress programming.
the Problem is with your initialization of the formmain.with out proper initialization the object you are creating is nothing other than Null.To avoid this we use New Operator.The New operator can often be used to create the instance when you declare it.
So the initialization will look like
Dim varMainForm As New FormMain
Hope this Helps.For more Reference Object Initialization Errors
update:
Dim varMainForm As FormMain //connecting the forms ?
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
hairdresser = HairdresserChoices(HairdresserID) // get the data
varMainForm = New FormMain
varMainForm.lstListBox.Items.Add(hairdresser) //Run time error breaks here.
Try This.
Public Class FormHairdresser //The second form
Private Sub btnAddHairdresser_Click(sender As Object, e As EventArgs) Handles btnAddHairdresser.Click
Dim varMainForm As FormMain
hairdresser = HairdresserChoices(HairdresserID)
varMainForm.lstListBox.Items.Add(hairdresser)

How to manipulate the SQL Server database from grid view (Form Application in VB.NET)

I need to control a database from grid view.
In another article I have to see how to manipulate a database, but there still used textbox and button for next process. In my case I need to control the data from grid view, so tell me please if you have solution for this problem.
Specifications:
application form
visual basic .NET 2010
SQL Server database
A quick search online found this: link. Below is the example code from that link showing how to display data.
If you want to do CRUD, please take a look at the Microsoft example here.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New OleDbConnection(connectionString)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
End Class

apparent bug when repopulating a datagridview

I have a created a simple example to illustrate what I have found. I also have a "fix", but I don't think I should need it!
I am using VS2010 and .NET 4. My form has a DataGridView (dgvTest), and a checkbox (CheckBox1). I am selecting 2 or 3 fields from a table, depending on whether the checkbox is checked (which it is initially).
My possible SQL statements are "SELECT ID,strForenames,strSurname FROM tblAlumni" and "SELECT strForenames,strSurname FROM tblAlumni".
I have used SQL Profiler to confirm that these are the queries sent to the DB.
All seems well when I load the form (I see 3 fields, in the order I expect), and when I uncheck the box (I see 2 fields, in the order I expect).
However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
I have found a couple of reports of something similar to this (mis)behaviour on the Net, but folks just seem to find some other way to do the job rather than ask is this a problem with DataGridView that needs fixed.
Since I have been able to recreate it with a simple example I have some confidence (only some!) that I am not missing anything obvious.
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System
Public Class Form1
Inherits System.Windows.Forms.Form
Dim sqlConn As SqlConnection
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
loadGRID()
End Sub
Private Sub loadGRID()
Dim sqlConn As SqlConnection = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True")
sqlConn.Open()
Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter("SELECT " & IIf(CheckBox1.Checked, "ID,", "") & "strForenames,strSurname FROM tblAlumni", sqlConn)
Dim ds As DataSet = New DataSet()
dataAdapter.Fill(ds)
dgvTest.DataSource = ds.Tables(0)
sqlConn.Close()
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
loadGRID()
End Sub
End Class
So my question is, do your experts agree this is a bug? The "fix" is to wipe the DataGridView between repopulations, but I'm not sure I should have to?
dgvTest.DataSource = Nothing
dgvTest.Refresh()
I have found a BindingSource as a glue between the 'datasource' and the datagridview works very nicely for me, sorry I know that doesn't answer whether this is a bug as I am not sure.
(c#)
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = ds.Tables(0);
bindingSource.ResetBindings(false);
However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
Thats the expected behaviour as the columns strForenames and strSurname already exist.
Try dgvTest.Columns.Clear() before and dgvTest.refresh after changing the datasource