Set up load event on windows form tab - sql

I am currently working in vb.net with windows form applications. I am using a multi-tab windows form where I want a data grid view to be loaded with information from an sql table as soon as the form opens. However, I can not find an event that uses the load feature coupled with the tab. Is there a way to hard code this?
...
Private Sub DataGridView1_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridLine2.CellContentClick
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("Select * FROM Production.dbo.tblOrdered", conn1)
Dim da As New SqlDataAdapter
da.SelectCommand = comm1
da.Fill(dt)
'select customerName as customer, contactname as contact person
'from cusomters;
End Using
conn1.Close()
End Using
DataGridLine2.DataSource = dt
Catch ex As Exception
MsgBox("Unable to make SQL Connection, please contact an engineer!")
MsgBox(ex.ToString)
End Try
End Sub
End Class

Related

How to link to a relational database - visual basic

I am creating a flashcard application where each user can create flashcards which will be specific to them. I was wondering how I can link each flashcard they create to their specific account.
Imports System.Data.OleDb
Public Class CreateFlashcards
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into Flashcards ([Front],[Back]) values ('" & txtFront.Text & "','" & txtBack.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(txtFront.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(txtBack.Text, String)))
MsgBox("You have successfully added the flashcard into your deck!")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtFront.Clear()
txtBack.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This works in that it adds the data into the access database but it does not link to the users account. I have also linked the tables in access
The login table
The flashcard table
As you can see the loginID key does not link
Normally, the connection string for Access contains the the path to the database file for the Data Source attribute.
You will need to add a field to your Flashcard table to hold the UserID. This will tie the 2 tables together.
Database objects like connections and commands need to be disposed as well as closed. Using...End Using blocks handle this for you even if have an error. In this code you both the connection and the command are included in the same Using block.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the sql command text and the connection to the constructor of the command.
When you are using parameters, which you should in Access and Sql Service, put the name of the parameter in the sql command text. It is not necessary to convert the Text property of a TextBox to a string. It is already a String.
I had to guess at the OleDbType for the parameters. Check your database. It is important to note that the order that parameters appear in the sql command text must match the order that they are added to the parameters collection. Access does not consider the name of the parameter, only the position.
I assume you can retrieve the user's ID when they log in to create flash cards. When the user logs in to use there flash cards you would do something like Select * From Flashcards Where LoginID = #UserID;.
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
Try
InsertFlashcard()
MsgBox("You have successfully added the flashcard into your deck!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub InsertFlashcard()
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Dim Command = " insert into Flashcards (LoginID, [Front],[Back]) values (#Id, #Front, #Back);"
Using myconnection As New OleDbConnection(pro),
cmd As New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserID", OleDbType.Integer).Value = ID
cmd.Parameters.Add("#Front", OleDbType.VarChar).Value = txtFront.Text
cmd.Parameters.Add("#Back", OleDbType.VarChar).Value = txtBack.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
EDIT
As per comment by ADyson I have added code to retrieve ID. Of course in your real application you would be salting and hashing the password. Passwords should never be stored as plain text.
Private ID As Integer
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Using cn As New OleDbConnection(pro),
cmd As New OleDbCommand("Select LoginID From login Where Username = #Username and Password = #Password;")
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = txtUserName.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Text
cn.Open()
Dim result = cmd.ExecuteScalar
If Not result Is Nothing Then
ID = CInt(result)
Else
MessageBox.Show("Invalid Login")
End If
End Using
End Sub

Add column to SQL table and populate to datagridview

I have a windows form application with databound datagridview. I want to add column at run time (if user wants to add more column to it). So on button click I wanted to add column. I have added following code to event it adds column in server explorer view under tables column's list but does not show in table definition neither in data source window (in column list under table) nor in datagridview.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Small_databaseDataSet.newtable' table. You can move, or remove it, as needed.
Me.NewtableTableAdapter.Fill(Me.Small_databaseDataSet.newtable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddColumn()
End Sub
Private Sub AddColumn()
Dim connString As String = "Data Source=(localDb)\ProjectsV13;Initial Catalog=small database;Integrated Security=True"
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Dim str As String = "ALTER TABLE newtable ADD " & TextBoxX1.Text & " INT null;"
Using comm As New SqlCommand(str, conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
End Using
Validate()
DataGridViewX1.Columns.Clear()
NewtableTableAdapter.Update(Small_databaseDataSet.newtable)
NewtableTableAdapter.Fill(Small_databaseDataSet.newtable)
DataGridViewX1.DataSource = NewtableBindingSource
End Sub
End Class
Change this line of code:
' Add the keyword NULL and brackets around the column name
Dim comm As New SqlCommand("ALTER TABLE testTable ADD [col1] INT NULL", conn)
If I wanted to have the new column to show up automatically, I would re-query the database, retrieving the data on that table and just set the datagridview datasource to the resultset like:
'I assume the datagridview name is DataGridView1
DataGridView1.Columns.Clear()
DataGridView1.DataSource = USTDatabaseDataSet
DataGridView1.DataMember = "testTable"
DataGridView1.DataBind()
A DataReader is used to retrieve data. Since there is no data retrieved nothing is loaded into your DataTable except maybe a return value of success or failure. The Using statements ensure that your objects are closed and disposed properly even if there is an error.
Private Sub AddColumn()
Dim connString As String = ConfigurationManager.ConnectionStrings("USTDatabaseConnectionString").ConnectionString
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Using comm As New SqlCommand("ALTER TABLE testTable ADD col1 INT;", conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
Using com2 As New SqlCommand("Select * From testTable;", conn)
Using reader As SqlDataReader = com2.ExecuteReader
dt.Load(reader)
conn.Close()
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

how to pass multiple values using single textbox in vb.net?

I am doing vb.net programming. In that, I am using one textbox, one gridview and one button. Now, I want to pass queries into the textbox and when clicking on button, I want to display the result into the datagridview.
i.e suppose i am passing selection query and clicking on button at that time i want to display the table data into the datagridview.
I don't know what Db you are using but I have an example using Sql.
Example:
You want to get the Name from the Students Db.
Dim dt As New DataTabale
Dim con As New SqlConnection("connection")
Dim cmd As New OdbcCommand("SELECT * FROM [Students] WHERE [Name] = #Name", con)
con.Open()
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox.Text
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView.DataBind()
You can place this code on Button.
Ps. I view your the edit history of your code and I saw that you are using Db.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim query As String = TextBox1.Text
Try
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
Catch ex As Exception
MsgBox("No results returned")
End Try
End Sub

Compare two datagridview and remove rows dependent on row properties

I am currently working in vb.net windows form applications. I have two DataGridViews and I want to cross reference the rows and remove certain rows out of datagridview1, depending on if a checkbox is checked in datagridview2. This problem arises when I check a box for an action taken by a front end user in datagridview1 that updates datagridview2. But, when I refresh both DataGridViews, datagridview2 shows that this action has been taken, but the checkbox column in datagridview1 goes back to unchecked, thus telling the front end user to repeat this action.
On a side note all the data is bound to an sql table, except the checkbox column in datagridview1. Also note, I have a refresh button that repeats the load event to refresh both tables.
Page Load Event Handler:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'load datagridview1'
Dim ds As New DataSet
Dim AA As New DataSet
connectionstring = "Data source = .\sqlexpress; integrated security = true"
connection = New SqlConnection(connectionstring)
sql = "SELECT Shear FROM production.dbo.stagingcompleted"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connectionstring)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'load datagridview2'
connectionstring = "Data source = .\sqlexpress; integrated security = true"
connection = New SqlConnection(connectionstring)
sql = "SELECT * FROM production.dbo.tblFCOrdered"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connectionstring)
adapter.Fill(AA)
connection.Close()
DataGridView2.DataSource = AA.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
DataGridView1 Event Handler (CellContentClick):
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
'update datagridview1 to the action for that row complete'
If e.ColumnIndex <> 0 Then
Exit Sub
End If
Dim v As String = DataGridView1.Rows(e.RowIndex).Cells(1).Value
Select Case MsgBox("Are you sure shear " & v & " has been cut?", MsgBoxStyle.YesNo)
Case MsgBoxResult.No
Exit Sub
Case MsgBoxResult.Yes
Try
Dim connstring = "Data Source=.\sqlexpress; integrated security = true"
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET FormChannel = 1 WHERE SHEAR = '" & v & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Select
I am possibly incorrect and I apologise if you have already tried this. I believe you might benefit from reading up about the page life-cycle, order event handlers and the effects of PostBack (for example this article)
In server controls, certain events, typically click events, cause the page to be posted back immediately to the server. Change events in HTML server controls and Web server controls, such as the TextBox control, do not immediately cause a post. Instead, they are raised the next time a post occurs.
In regards to PostBack and Page.Load:
After a page has been posted back, the page's initialization events (Page_Init and Page_Load) are raised, and then control events are processed. You should not create application logic that relies on the change events being raised in a specific order unless you have detailed knowledge of page event processing.
I think that part of the problem you are experiencing is that the first thing the page will do when you trigger a PostBack, e.g. by clicking on a cell, is the code which you have in your Page.Load event handler. In your code you will find that when the page is processed (on PostBack) the first thing that happens is that the grids are data bound. Because of this any changes made will not be persisted when the other event handlers are called. A common check before performing actions such as data binding in the Page.Load function is to check that the page is not being posted back, if IsPostBack = true it is likely that you will want to skip such actions.

Datagridview doesn't clear or replace the previos data vb.net

Can't find the way to replace the previous data with the new one....
I use a button to view my table in dgv. When I click the button twice for viewing my table it only show the data next with the previous one
Here's the code that I'm using
Private Sub cmdview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdview.Click
connetionstring = "Integrated Security = SSPI; data source= DELL-PC;Initial catalog=Library System"
connection = New SqlConnection(connetionstring)
sql = "select * from dbo.tblbook"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
connection.Close()
dtg1.DataSource = ds.Tables(0)
Return
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx
"Tables and columns are only created if they do not already exist; otherwise Fill uses the existing DataSet schema. "
Meaning if you have data in your dataset it will not be overwritten if you use fill. So try this before your adapter.Fill line:
ds.Clear()