How to manipulate the SQL Server database from grid view (Form Application in VB.NET) - 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

Related

VB.Net Inserting DateTimePicker to MS Access Database

Good day to everyone here at stackoverflow! I have a simple question that maybe you guys could help me out with. I created a prototype for inserting a DateTimePicker into the MS Access database. I followed this guide:
date time conversion problem when inserting data into sql database and although it helped the person asking the question, it did not help me at all :(
This is the picture and this is my code. This is just a simple prototype that if solved, I will be able to implement it into the actual system I am working on with my classmates.
There is a syntax error apparently. But if I remove just the datetimepicker codes I can insert my last name without any problems and have it show up in MS Access. These are the codes.
Imports System.Data.OleDb
Public Class Form1
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Israel De Leon\Documents\dateinsert.accdb;"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim cmd As OleDbCommand
Dim adapter As OleDbDataAdapter
Dim dt As DataTable = New DataTable()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListView1.View = View.Details
ListView1.FullRowSelect = True
ListView1.Columns.Add("Last Name", 100)
ListView1.Columns.Add("Date", 100)
End Sub
Public Sub add()
Dim SQL As String = "INSERT INTO Table1(LastName, Time) VALUES (#LastName, #Time)"
cmd = New OleDbCommand(SQL, con)
cmd.Parameters.AddWithValue("#LastName", TextBox1.Text)
cmd.Parameters.AddWithValue("#Time", DateTime.Parse(DateTimePicker1.Value))
'OPEN CONNECTION AND INSERT
Try
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("Succesfully Inserted")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
add()
End Sub
End Class
Please help this mate out. Thank you :D
The problem is the name of the column Time. Time is a reserved word in MS-Access. You need to put square brackets around that name
Dim SQL As String = "INSERT INTO Table1(LastName, [Time]) VALUES (#LastName, #Time)"
I also strongly suggest you to not use AddWithValue, but the more precise Add where you can properly set the datatype of your parameter and avoid the hidden code of AddWithValue that translates your inputs to the expected ones
cmd.Parameters.Add("#LastName", OleDbType.VarWChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#Time", OleDbType.DateTime).Value =DateTimePicker1.Value
Notice that the Add method allows you to define also the size of your data in case of text. This allows the database engine to optimize your insert query. (Not sure if this happens also with access but surely with Sql Server this is an important optimization)
Better to use monthCalendar control:
textBox1.Text = monthCalendar1.SelectionRange.Start.Date.ToShortDateString()
cmd.Parameters.AddWithValue("#Time", textBox1.Text)

Visual Basic Connect to Access DataBase

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?

How do I transfer data from Text Boxes in a form to an Access Table

I'm currently trying to write code for a form that has text boxes for a user to input the required data into which then with the use of button the data in the text boxes will be sent to an access table.
If you need any more information to help solve the problem I'm willing to provide it if you ask (I would upload pictures/screenshots but I need "10 reputation" apparently.
You can do this
Imports System.Data.OleDb
Public Class Form1
Dim AccessConection As OleDbConnection
Private Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
Dim cmd As New OleDbCommand
Dim mySql As String
mySql = "INSERT INTO Customs (CustomName,Address) VALUES(#Name,#Address)"
Try
cmd.Parameters.AddWithValue("#Name", txName.Text)
cmd.Parameters.AddWithValue("#Address", txAddress.Text)
cmd.Connection = AccessConection
cmd.CommandType = CommandType.Text
cmd.CommandText = mySql
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Whatever you want to say..." & vbCrLf & ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myDataBasePath As String = "C:\Users\user\Source\Workspaces\......\SOF003\Data.accdb" 'Here you put the full name of the database file (including path)
'The next line is for Access 2003 .mdb files
'Dim CadenaConection As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", myDataBasePath)
Dim CadenaConection As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", myDataBasePath)
AccessConection = New OleDbConnection(CadenaConection)
AccessConection.open()
End Sub
End Class
btSave is the command button.
Customs is the table's name.
CustomName and Address are two fields.
txName and txAddress are two TextBox Control.
Obviously you should be careful with the data types (here I use only strings), validation, etc, etc... But, this is a starting point. If you search, you'll find another ways, more elaborated.

how to open database connection in 1 form then close it in another form?

Public Class Login
Private Shared con As New OleDb.OleDbConnection
Dim sql As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text <> "fcf#gmail.com" Or TextBox2.Text <> "fcf1234567" Then
MsgBox("Wrong username or password!! Please try again!!", 0, "!!!")
Else
con.Open()
sql = "SELECT * FROM c_info"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "c_information")
Me.Hide()
Home.Label6.Show()
Home.Label6.Text = ds.Tables("c_information").Rows(0).Item(0)
Home.Button8.Show()
Home.Button6.Hide()
Home.Button9.Show()
Profile.Enabled = True
Profile.TextBox1.Text = ds.Tables("c_information").Rows(0).Item(0)
Profile.TextBox2.Text = ds.Tables("c_information").Rows(0).Item(1)
Profile.TextBox3.Text = ds.Tables("c_information").Rows(0).Item(2)
Profile.TextBox4.Text = ds.Tables("c_information").Rows(0).Item(3)
Profile.TextBox5.Text = ds.Tables("c_information").Rows(0).Item(4)
Profile.ComboBox1.Text = ds.Tables("c_information").Rows(0).Item(5)
End If
End Sub
I'm doing a log-in system, try to open database connection then close it in another form, no idea how to do it...in this code i have typed con.open(), but when i run it twice, it says "current connection still open"
3 Suggestions:
(Less recomendable) Change con to Public Shared or Protected Shared (preferable to have it on a separate class/module); this way you'll be able to access it from all your forms and clases
(Most adecuate to your scenario) Add a property on your 2nd form of OleDb.OleDbConnection or a parameter on its constructor and pass it from Form1 when you create the second form.
(Most recommended) Rethink your design and logic. Having an open database connection wandering over all your program is a bad idea for many reasons. Create a database connection on every form/class you need one, open and close it as soon as you use it.

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