how to update database using DataGridView - vb.net

Basically i have a datagridview which is filled by a query upon the loading of the page to display all the incomplete orders in my database table as below:
I was wondering if it's possible to allow the user to edit them so they can mark the incomplete orders as completed, i was thinking through either just allowing the column to be editable, or maybe a set of checkboxes alongside each row which would mark them as completed.
here's my current code the page:
Public Class processorders
Dim sql As New sqlcontrol
Private Sub ammendorders_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sql.HasConnection = True Then
sql.RunQuery("SELECT customers.customer_id, first_name, second_name, phone_number, date_ordered, order_total, collection_method FROM (Orders INNER JOIN Customers on orders.customer_id = customers.customer_id) WHERE order_status='In Progress'")
If sql.sqldataset.Tables.Count > 0 Then
dgvData.DataSource = sql.sqldataset.Tables(0)
End If
End If
End Sub
'above queries database to find all incomplete orders
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub

If you wanted to edit the order_status field, you could set the the column as a DataGridViewComboBox which would contain all possible status values. Then create an event handler to update the database when the combo box value is changed.
Edit: Code
Private Sub MyDataGridView_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles MyDataGridView.RowValidated
'update the data source here, could vary depending on the method used.
if sql.HasConnection
Dim sqlCmd as SqlCommand = new SqlCommand
sqlCmd.connection = "<Your connection string>"
sqlCmd.commandText =
String.format(
"UPDATE Orders SET order_status='{0}' WHERE customer_id='{2}';",
MyDataGridView.Rows(e.RowIndex).Cells(<order_status column index>).Value,
MyDataGridView.Rows(e.RowIndex).Cells(<customer_id column index>).Value
)
sqlCmd.ExecuteNonQuery
end if
End Sub
Edit 1: Found another possible answer: DataGridView Cell Editing and Updating DB (C#)
Edit 2: Changed sql.RunQuery to a SqlCommand object.

This is how I do it. This is hooked to a dropdown list but it can be hooked to any control in the grid:
' This enables you to capture the Update event on a gridview
Dim clickedRow As GridViewRow = TryCast(DirectCast(sender, DropDownList).NamingContainer, GridViewRow)
Dim cust_id As Label = DirectCast(clickedRow.FindControl("lbl_grd_id"), Label)
Dim status As DropDownList = DirectCast(clickedRow.FindControl("ddl_grd_crew_id"), DropDownList)
Dim cmd As New SqlCommand()
cmd.CommandText = "UPDATE [your_orders_table] set status = #status where customer_id = #cust_id "
cmd.Parameters.Add("#cust_id", SqlDbType.Int).Value = Convert.ToInt32(cust_id.Text)
cmd.Parameters.Add("#status", SqlDbType.VarChar).Value = status.Text
cmd.CommandType = CommandType.Text
cmd.Connection = Me.sqlConnection1
Me.sqlConnection1.Open()
'execute insert statement
cmd.ExecuteNonQuery()
Me.sqlConnection1.Close()
're-populate grid with a method call. if you don't the edits will not be reflected when the grid reloads
fill_order_status_grd()
fill_order_status_grd.databind()

Related

How do relationships work and how can I implement it in my project?

I have a User table and Institutions table. I have put made a relationship with those two in access. Inst id is now in user table as a foreign key.
In my vb form, i populate a combobox with the institution names from inst table. When I select a username from a list box, his/hers relevant details are captured into textboxes on the form. But I dont know how to capture the Institution name using the foreign key.
'actions when listbox selection is changed
Private Sub listbox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
cbInst_putData()
cbAccountType_putData()
If gbEditUser.Visible = True Then
Dim selected_item As String = ListBox1.SelectedItem
qr = "Select * FROM [User] WHERE Username = '" & selected_item & "'"
Using cn As New OleDbConnection(cnString)
cn.Open()
Using cmd As New OleDbCommand(qr, cn)
Dim reader As OleDbDataReader = cmd.ExecuteReader
While reader.Read
txtFirstname_edit.Text = reader.Item("Firstname").ToString
txtLastname_edit.Text = reader.Item("Lastname").ToString
txtAddress_edit.Text = reader.Item("Address").ToString
txtPhone_edit.Text = reader.Item("Phone").ToString
Dim dt As Date = Date.Parse(reader.Item("DateofBirth").ToString)
txtdob_edit.Text = dt
txtUsername_edit.Text = reader.Item("Username").ToString
txtPassword_edit.Text = reader.Item("Password").ToString
cbAccountType_edit.SelectedItem = reader.Item("AccountType").ToString
cbInst_edit.Text = reader.Item("InstitutionIDFK").ToString ' this is the combobox for institution list.
txtDesc.Text = reader.Item("Description").ToString
Dim checkActive As String
checkActive = reader.Item("Active").ToString
End While
End Using
cn.Close()
End Using
End If
End Sub
I want to store the institution name in the user table and also be able to capture it again. I did it without making a relationship before. By just having a institution field separately in the user table.
Im very new to vb. And completely new to posting on here even though ive been looking at other questions on this site. So please excuse me if my codes are bad and if im not posting properly.
Pretend that my Roasters are institutions and my Coffees are Users.
I bind the list box and the combo box to the data in the Form.Load.
When the selection in the ListBox is changed we get the RoasterId (the Foreign Key) associated with the selection. Next we loop through the items in the combo box Primary Key in the ID field. When we get a match, select that item and exit the loop.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim RoastersSql = "Select * From Roasters;"
Dim CoffeesSql = "Select Top 10 * From Coffees;"
Dim RoastersDT As New DataTable
Dim CoffeeDT As New DataTable
Using cn As New SqlConnection(ConGD)
Using cmd As New SqlCommand(RoastersSql, cn)
cn.Open()
Using reader = cmd.ExecuteReader
RoastersDT.Load(reader)
End Using
End Using
Using cmd As New SqlCommand(CoffeesSql, cn)
Using reader = cmd.ExecuteReader
CoffeeDT.Load(reader)
End Using
End Using
End Using
ListBox1.DisplayMember = "Name"
ListBox1.ValueMember = "ID" 'NOT the RoasterID, this is th PK of the Coffees table
ListBox1.DataSource = CoffeeDT
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = RoastersDT
UpdateUI(ListBox1.SelectedItem)
End Sub
Private Sub FillTextBoxes(item As Object)
Dim drv = DirectCast(item, DataRowView)
TextBox1.Text = drv("Name").ToString
TextBox2.Text = drv("Type").ToString
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
UpdateUI(ListBox1.SelectedItem)
End Sub
Private Sub UpdateUI(item As Object)
Dim RoasterID = CInt(DirectCast(ListBox1.SelectedItem, DataRowView)("RoasterID"))
For Each item In ComboBox1.Items
Dim ID = CInt(DirectCast(item, DataRowView)("ID"))
If RoasterID = ID Then
ComboBox1.SelectedItem = item
Exit For
End If
Next
FillTextBoxes(ListBox1.SelectedItem)
End Sub
Do the following:
Make sure that you created a relationship (one-to-many).
Create a new query and add both tables.
Add all the fields from both tables in the query (except for the foreign key).
Make the query the data source of your Form.

Automatically update an ID label

I am working on making a label inside my Windows Form to display new ID automatically. My label was connected to an access database and I want to make the label to display new ID after the last record of ID inside my database. For example, the last record is 'tt0005061' from Movie table. The label should display a new ID, 'tt0005062'.
Public Class Movies_Registration_Form
Dim index As Integer = 0
Private Sub Movies_Registration_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
showData(index)
End Sub
Public Sub showData(position As Integer)
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=1MDb.accdb;Persist Security Info=False;")
strSQL = "SELECT RIGHT(tconst,7) From Movie ORDER BY tconst DESC"
cmd = New OleDbCommand(strSQL, conn)
da = New OleDbDataAdapter(cmd)
da.Fill(table)
lblMovieID.Text = "tt" & table.Rows(0)(0).ToString()
End Sub
The output of the label should be in an increment form, meaning that it should be +1 from the last record inside my database.
Try with:
lblMovieID.Text = (Integer.Parse(table.Rows(0)(0)) + 1).ToString("tt0000000")

Populate check boxes in DataGridView based on database values vb.net

PLEASE SEE CLEARER EDITED CODE POINTED OUT BELOW TO BE MORE SPECIFIC ON WHERE HELP IS NEEDED.
What I am trying to accomplish is this: I have a DataGridView that is using a DataAdapter to fill with the DataTable. I have hard-coded a separate DataGridViewCheckBoxColumn to come first. The DataGridView columns are as follows (in order):
[0]"ADD" (hard-coded `DataGridViewCheckBoxColumn`)
[1]"Job No" (from sql database)
[2]"Project No" (from sql database)
[3]"Project Name" (from sql database)
I also have a ComboBox populated with usernames from a separate database (but the two have a common key - userId, associating them with which user has admin privileges to edit that particular project in another form). The purpose of this form is to add a project to that user so they can have admin rights to edit additional projects.
I need for the DataGridView to fill with ALL projects, and have the DataGridViewCheckBoxColumn populate '.checked = true' for the projects according to which ones the userId is already associated with having admin privileges (according to existing info in the database). Then I need to have the ability to ADD new projects but checking new checkboxes, then clicking btnUpdate, and updating the database accordingly.
I have been able to populate the DataGridView, create the DataGridViewCheckBoxColumn, make that column NOT readonly, but I can't get it to check the boxes that are associated with the projects, and so on... below is the code... please help?
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'there is where usernames will be filled into dropdown from Proj_users database
Dim fillUName As New SqlCommand("SELECT UName FROM Proj_User WHERE Active = 1 and Admin = 1", frmConnect.DB)
Dim dr As SqlDataReader = fillUName.ExecuteReader()
While dr.Read()
If dr.HasRows = True Then
cmbAddUName.Items.Add(dr("UName"))
End If
End While
dr.Close()
End Sub
Private Sub cmbAddUName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbAddUName.SelectedIndexChanged
Call fillAddGrid(cmbAddUName.Text)
End Sub
Sub fillAddGrid(ByVal PT_User As String)
'column created for checkbox (to be able to check additional projects that will then be added to the user indicated in the combobox's privileges - let's them be able to change that project's details in another form)
Dim chk As New DataGridViewCheckBoxColumn()
grdAddProjectPrivs.Columns.Add(chk)
chk.FalseValue = False
chk.TrueValue = True
chk.HeaderText = "Add"
chk.Name = "Add"
chk.ReadOnly = False
'use stored procedure with parameter to generate recordset
Dim sqlCmd As New SqlCommand
sqlCmd.Connection = frmConnect.DB
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "SP_ManagePrivs"
'IF #SP_Use = 3 -- for ADDING privileges, FILL GRID with ALL projects so can add which ones they need
'BEGIN()
' SELECT
' P.JobNo AS [Job No],
' P.ProjNo AS [Project No],
' P.ProjName AS [Project Name]
' FROM Projects P JOIN User_Projects UP ON P.JobNo = UP.JobNo
' WHERE P.Deleted = 0 and P.Active = 1
' ORDER BY UP.UserID, P.JobNo
'End
'for adding privs, need to show all projects
sqlCmd.Parameters.Add(New SqlParameter("#SP_Use", 3))
sqlCmd.Parameters.Add(New SqlParameter("#UName", DBNull.Value))
sqlCmd.Parameters.Add(New SqlParameter("#Active", DBNull.Value))
sqlCmd.Parameters.Add(New SqlParameter("#Admin", DBNull.Value))
sqlCmd.ExecuteNonQuery()
'use DataAdapter to fill datatable
Dim sqlDA As New SqlDataAdapter()
sqlDA.SelectCommand = sqlCmd
Dim table As New DataTable
sqlDA.Fill(table)
grdAddProjectPrivs.DataSource = table
sqlDA.Dispose()
'reading to get userid to checkboxes accordingly
Dim userID As New SqlCommand("SELECT JobNo FROM User_Projects WHERE PT_User = '" & cmbAddUName.Text & "'", frmConnect.DB)
Dim dr As SqlDataReader = userID.ExecuteReader()
'****THIS IS WHERE I THINK I NEED HELP!!!!
While dr.Read()
If dr.HasRows = True Then
If grdAddProjectPrivs.Columns.Contains(dr("JobNo")) Then
For Each row As DataGridViewRow In grdAddProjectPrivs.Rows
row.Cells("Add").Value = True
Next
End If
End If
End While
dr.Close()
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
'HERE I AM LOOKING TO UPDATE THE DATABASE BY ADDING THE USER'S UserID number TO THAT SPECIFIC PROJECT THAT THEY CHECK OFF WITH THE CHECKBOX.
'i'm thinking once i get the gist of manipulating the checkboxes down pat i can figure this out but if there is anything additional i need to know please advise?
End Sub
End Class
Breakdown of SQL tables' layouts:
USER_PROJECTS TABLE CONSISTS OF (UserID, UserName, JobNo); PROJECTS TABLES CONSISTS OF (UserID, JobNo, ProjNo, ProjName)

how to update, insert records through datagridview to sql using data adapter or other method in vb.net

hello best programmers in the world i need your expert advise and assistance with regards to my project.
I am trying to insert and update my table through datagridview by clicking a command button,
i have my datagridview properties set to editmode : editprogrammatically,
here's the code, of where i pulled up my datagridview content:
Public Sub loaddgvfrm3()
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = sqlstr
cmdconn.Open()
cmd.Connection = cmdconn
cmd.CommandText = "select period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO from tobee.EBD_BILLHISTORY where CLAIM_NO like '" + txtClaimno.Text + "'"
Dim dt As New DataTable
da = New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
Me.DataGridView2.DataSource = dt
cmdconn.Close()
End Sub
now i have my command buttons here
here's the add button: (im prefering to add a row within the selected table)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
End Sub
here's the Edit button:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
''Form1.ShowDialog()
'DataGridView2.AllowUserToAddRows = True
''DataGridView2.BeginEdit(True)
'btnSave.Enabled = True
End Sub
and here's the save button that should save all changes that i have done,
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=midtelephone\sqlexpress; database=testdb; user= sa; password=sa;"
End Sub
i left command button contents empty because i need to create a new method of inserting, updating the row. because the one that i have earlier was a fail, although it inserts the data in the sql, but not in its appropriate row, take a look at here: Data inserted from datagridview not updated in SQL Server , instead it creates another row which is not connected with '" + txtClaimno.Text + "'" (stated from above) so what happens is that it stacks a new row with no connected owner from another table(claim_no < this claim_no is connected from another table as a fk in the database but a primary key in (billhistory table))
can you pls help me get rid of this problem as i am having a hard time moving to the next phase of our project? im just a high school student, so pls bear with me :) i'll appreciate if u give comments / answers regarding my question :) thanks in adv.
my mentor advised me to use data adapter accept changes stuff, but i don't know how to implement such stuffs. pls help me thank you :)
Use Event to get data from gridview on cellConttent Click and these values to a query or Stored procedure.
private void grdCampaignStats_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//I want to get value of SomeColumn of grid view having datatype String
string SomeVariabel = grd["CoulmnNameinGRID", e.RowIndex].Value.ToString();
// Make it according to Vb it is C# code
}

displaying detailed form based on textbox value and a button

i have a form named "search" with 2 textboxes,datagridview and a buttton. when i enter any keyword such as a name i want into the first textbox ["txtemployee_search"], it filters the datagridview [dgvemployee]items which is binded to the employee table.so when i select the name im looking for, it shows up in the second textbox["txtemp_search_selection"].but MY PROBLEM IS, I WANT TO SHOW OR OPEN A SECOND FORM CONTAINING THE DETAILS like name,age,sex,picture,phone,etc which are related to the name in the second textbox WHEN I CLICK THE BUTTON. im using vb 2008 and sql server 2005.I NEED HELP PLS!!!
below is my code
Imports System.Data.SqlClient
Public Class employee_search
'THE CODE TO SEARCH DATAGRID WHILE TYPING INTO FIRST TEXTBOX
Private Sub txtemployee_search_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtemployee_search.TextChanged
Dim keywords As String = txtemployee_search.Text
Dim con As SqlConnection = New SqlConnection("Data Source=oheneba;Initial Catalog=brainiac;Persist Security Info=True;User ID=sa;Password=***********")
' Use wildcard
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Employee WHERE Full_Name Like '%" & keywords & "%' ", con)
' or Where Full_Name='" & keywords & "'
con.Open()
Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Employee")
dgvemployee.DataSource = myDataSet.Tables("Employee").DefaultView
con.Close()
End Sub
'CODE TO DISPLAY SELECTED DATAGRIDVIEW ITEM INTO THE SECOND TEXTBOX
Private Sub dgvemployee_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvemployee.CellContentClick
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim thisCell As DataGridViewCell = dgv.SelectedCells(0)
Dim selCell As Integer = thisCell.ColumnIndex
txtemp_search_selection.Text = dgvemployee.CurrentRow.Cells(selCell).Value.ToString()
End Sub
The approch is a bit diffrent that you should choose.
Sorry if i'm wrong but i'll wive you an example with 2 grids. one with customers and one with orders (the relation must be right on the DB). So use 2 BindingSource objects. one with Customers and one with Orders.
so we have
CustomersBindingSource
OrdersBindingSource
Set on property window
CustomersBindingSource.Datasource = yourDataset
CustomersBindingSource.DataMember = Customers
OrdersBindingSource.Datasource = OrdersCustomersfkBindingSource
and about filtering the way that i suggest is this one:
CustomersBindingSource.filter = "Customername like " & txtCustomFilter
i'm in a little hurry now.. but if you have more questions i'll be happy to help you.
If you want additional details in another form, then what you need to do is create the second form with the details. Add in databinding, just like you did for the datagridview, and navigate to the correct record. You should be able to pass the full name selected from the datagridview into the new form.
tIndex = Me.MyBindingSource.Find("Full_Name", keywords)
If tIndex = -1 Then 'could not find
'employee not found
Else
Me.MyBindingSource.Position = tIndex 'navigate to found record
End If
CODE TO DISPLAY SELECTED DATAGRIDVIEW ITEM INTO THE SECOND TEXTBOX
Try this ..
txtemp_search_selection.Text = dgvemployee.CurrentCell.Value