Edit cell on a DataGridView - vb.net

How can I edit a cell on a DataGridView? When I run the project I want to edit the cell and then click a Button.
This is my code:
Public Class Form1
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=db.accdb")
'SELECT employ.id, employ.name, employ.adress, employ.phone FROM employ;
Sub New()
' This call is required by the designer.
InitializeComponent()
loadAll()
' Add any initialization after the InitializeComponent() call.
End Sub
Sub loadAll()
Dim da As New OleDbDataAdapter("SELECT employ.id, employ.name, employ.adress, employ.phone FROM employ;", con)
Dim dt As New DataTable()
da.Fill(dt)
DataGridView1.Rows.Clear()
For x = 0 To dt.Rows.Count - 1
DataGridView1.Rows.Add()
DataGridView1(0, x).Value = dt.Rows(x)(0).ToString()
DataGridView1(1, x).Value = dt.Rows(x)(1).ToString()
DataGridView1(2, x).Value = dt.Rows(x)(2).ToString()
DataGridView1(3, x).Value = dt.Rows(x)(3).ToString()
Next
End Sub
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
DataGridView1.ReadOnly = False
DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.ReadOnly = True
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim name As String = DataGridView1(1, i).Value.ToString()
Next
Dim Str As String = String.Format("update employ set name='{0}' where id= i", Name, DataGridView1(0, DataGridView1.SelectedRows(0).Index).Value.ToString())
Dim cmd As New OleDbCommand(Str, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
How can this be done please?

Related

how can i fix this error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

I have a gridview when i click the column of the dataGridview the problem show
"error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index""
how can i fix this? please help
this is the whole code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'construct dataGridview
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "name"
DataGridView1.Columns(1).Name = "position"
DataGridView1.Columns(2).Name = "team"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
End Sub
Private Sub Populate(name As String, pos As String, team As String)
Dim row As String() = New String() {name, pos, team}
DataGridView1.Rows.Add(row)
End Sub
Private Sub Retrieve()
DataGridView1.Rows.Clear()
Dim sql As String = "SELECT * FROM peopleTB"
cmd = New OleDbCommand(sql, con)
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.fill(dt)
'fill dgview
For Each row In dt.Rows
Populate(row(1), row(2), row(3))
Next
con.Close()
dt.Rows.Clear()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Cleartxt()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
'update db and dg
Private Sub UpdateDG(name As String)
Dim sql As String = "UPDATE peopleTB Set N ='" + TextBox1.Text + "',P='" + TextBox2.Text + "',T='" + TextBox3.Text + "'WHERE N= '" + name + "'"
'OPEN CON
Try
con.Open()
adapter.updateCommand = con.CreateCommand()
adapter.updateCommand.commandtext = sql
If adapter.updateCommand.executenonquery() > 0 Then
MsgBox("Success updated")
Cleartxt()
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(2).Value
TextBox1.Text = name
TextBox2.Text = position
TextBox3.Text = team
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(name)
End Sub
Im using ms access

How do I put the items I picked in listview to my database?

See pic
Just new to vb.net. Anyway, I don't know how I will put the value of product and price I picked in the database since it's in the list view. I tried
Dim txtValue as String
txtValue = ListView1.FocusedItem.SubItems(0).text. To get the values of the columns.
In the picture I provided, If I the put the customername and I pick her order in the listview1 it will save in my database. And it will show it my listview2. Just disregard the address.
UPDATE I think this code works but there's still error message showing up.Error message see pic
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection = New SqlConnection("server=.\SQL;database=try;Trusted_Connection=TRUE")
Dim cmd As SqlCommand
Dim cmd2 As SqlCommand
Dim rdr As SqlDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
con.Close()
list()
list2()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM ProductTable", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(2) {}
Dim itm As ListViewItem
arr(0) = rdr("productID")
arr(1) = rdr("product")
arr(2) = rdr("price")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
modifyrecord("Insert into ProductOrder([name],[product],[price]) values ('" & txtname.Text & "','" & ListView1.SelectedItems(0).SubItems(1).Text & "'," & ListView1.SelectedItems(0).SubItems(2).Text & "")
End Sub
Private Sub listView1_MouseClick_1(ByVal sender As Object, ByVal e As MouseEventArgs)
End Sub
Sub list2()
con.Open()
cmd2 = New SqlCommand("SELECT * FROM ProductOrder", con)
rdr = cmd2.ExecuteReader
ListView2.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(3) {}
Dim itm As ListViewItem
arr(0) = rdr("id")
arr(1) = rdr("name")
arr(2) = rdr("product")
arr(3) = rdr("price")
itm = New ListViewItem(arr)
ListView2.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Sub modifyrecord(ByVal sql)
If txtname.Text = "" Or ListView1.SelectedItems(0).SubItems(1).Text = "" Or IsNumeric(ListView1.SelectedItems(0).SubItems(2).Text) = False Then
Else
con.Open()
cmd = New SqlCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
list()
End If
End Sub
End Class
Try this
txtValue = ListView1.SelectedItems(0).SubItems(1).Text
txtValue1 = ListView1.SelectedItems(0).SubItems(2).Text
To get the Product and price from the list view
I assume you have the MultiSelect set to false.

Datagridview Horizontal to vertical button

The following code isn't working when exporting the datagridview data when trying to make it vertical with headers along the left side along with text beside each one. Once this is flipped the user would click on button1 to export to excel.
Imports System.Data.DataTable
Imports System.IO
Imports Microsoft.Office.Interop
Public Class Form1
Dim table As New DataTable(0)
Public checkBoxList As List(Of CheckBox)
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet()
dt = New DataTable()
ds.Tables.Add("Table")
Dim my_DataView As DataView = ds.Tables(0).DefaultView
DataGridView1.DataSource = my_DataView
table.Columns.Add("Forename", Type.GetType("System.String"))
table.Columns.Add("Surname", Type.GetType("System.String"))
table.Columns.Add("Food", Type.GetType("System.String"))
checkBoxList = New List(Of CheckBox) From {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim values As String = "" &
String.Join(" & ", checkBoxList _
.Where(Function(cb) cb.Checked).Select(Function(cb) cb.Text))
' use values for placing into your DataGridView
CheckBox1.Text = values
CheckBox2.Text = values
CheckBox3.Text = values
CheckBox4.Text = values
table.Rows.Add(TextBox1.Text, TextBox2.Text, values.ToString)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowTemplate.Height = 100
DataGridView1.AllowUserToAddRows = False
DataGridView1.DataSource = table
'Save to excel with headers
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(1, column.Index + 1) = column.HeaderText
Next
For i = 1 To Me.DataGridView1.RowCount
.cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("Forename").Value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
End With
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Public Function FlipDataSet(ByVal my_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In my_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
When clicking button2 it should flip the data with the following;
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
I've tried debugging but it i can't seem to find anything wrong? It will allow me to insert data in the textbox's whilst selecting checkbox's and when clicking button 1 to export it works fine, but it doesn't flip the data.
Please can anyone suggest how to fix this as i have a presentation on the 8th June and this data needs to automatically be flipped
Sourcecode: Download Myproject
Image of target
Answered:
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices
Public Class Form1
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
dt = New DataTable("MyTable")
dt.Columns.Add("Forename", Type.GetType("System.String"))
dt.Columns.Add("Surname", Type.GetType("System.String"))
dt.Columns.Add("Food", Type.GetType("System.String"))
ds = New DataSet
ds.Tables.Add(dt)
Dim my_DataView As DataView = ds.Tables("MyTable").DefaultView
DataGridView1.DataSource = my_DataView
End Sub
Private Sub Button_AddRowData_Click(sender As Object, e As EventArgs) Handles Button_AddRowData.Click
Dim foods As String = String.Join(" & ", CheckedListBox1.CheckedItems.Cast(Of String))
dt.Rows.Add(New Object() {TextBox_Forename.Text, TextBox_Surname.Text, foods})
End Sub
Private Sub Button_FlipAndSave_Click(sender As Object, e As EventArgs) Handles Button_FlipAndSave.Click
FlipAndSave(ds.Tables("MyTable"))
End Sub
Private Sub FlipAndSave(table As DataTable)
Dim ExcelApp As New Excel.Application
Dim WrkBk As Excel.Workbook = ExcelApp.Workbooks.Add()
Dim WrkSht As Excel.Worksheet = CType(WrkBk.Worksheets(1), Excel.Worksheet)
With WrkSht
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, 1) = table.Columns(ci).ColumnName
Next
For ri As Integer = 0 To table.Rows.Count - 1
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, ri + 2) = table.Rows(ri).Item(ci).ToString
Next
Next
End With
ExcelApp.Visible = True
'use this lines if you want to automatically save the WorkBook
'WrkBk.SaveAs("C:\Some Folder\My Workbook.xlsx") '(.xls) if you have an old version of Excel
'ExcelApp.Quit() 'use this line if you want to close the Excel Application
ReleaseObject(ExcelApp)
ReleaseObject(WrkBk)
ReleaseObject(WrkSht)
End Sub
Private Sub ReleaseObject(obj As Object)
Marshal.ReleaseComObject(obj)
obj = Nothing
End Sub
End Class

DataGridView Cell Value Change Not Happening untill i call from button click

I have retrieved Product List from access database into a DataGridView. here is code:
Sub loadProductList()
Try
Using dbConn As New OleDb.OleDbConnection
dbConn.ConnectionString = dbProvider & dbSource
dbConn.Open()
Dim thisSQL As String
thisSQL = "SELECT productID, productName, productCostPrice From " & tblProduct & " WHERE productBrandID=" & CType(txtBrandName.Tag, Integer)
Dim Dadapter As New OleDbDataAdapter(thisSQL, dbConn)
Dim DSet As New DataSet
Dadapter.Fill(DSet, tblProduct)
With DataGridView1
.Columns.Clear()
.DataSource = DSet.Tables(tblProduct)
With .Columns.Item(0)
.Width = 50
.HeaderText = "Code"
.Name = "Code"
End With
Dim txtColumn As New DataGridViewTextBoxColumn
With txtColumn
.Width = 50
.HeaderText = "Qty"
.Name = "Qty"
End With
.Columns.Insert(1, txtColumn)
With .Columns.Item(2)
.Width = 490
.HeaderText = "Description"
End With
With .Columns.Item(3)
.Width = 100
.HeaderText = "Price"
.Name = "Price"
.DefaultCellStyle.Format = "N"
End With
Dim txtaColumn As New DataGridViewTextBoxColumn
.Columns.Insert(4, txtaColumn)
With .Columns.Item(4)
.Name = "Amount"
.HeaderText = "Amount"
.Width = 120
.DefaultCellStyle.Format = "N"
End With
End With
End Using
Catch ex As Exception
End Try
End Sub
Sub UpdatePurchaseItemList()
Try
Using dbConn As New OleDb.OleDbConnection
dbConn.ConnectionString = dbProvider & dbSource
dbConn.Open()
Dim thisSQL As String
thisSQL = "SELECT * FROM " & tblPurchaseItems & " WHERE PitemPID='" & txtRefID.Text & "'"
Using dbDataCmd As New OleDbCommand(thisSQL, dbConn)
Dim dbDataRead As OleDbDataReader
dbDataRead = dbDataCmd.ExecuteReader()
Do While dbDataRead.Read = True
For i As Integer = 0 To DataGridView1.Rows.Count - 1
With DataGridView1.Rows(i)
If .Cells("Code").Value = dbDataRead("PitemProductID") Then
.Cells("Qty").Value = dbDataRead("PitemProductQty")
.Cells("Price").Value = dbDataRead("PitemCost")
.Cells("Amount").Value = dbDataRead("PitemTotal")
Exit For
End If
End With
Next
Loop
End Using
End Using
Catch ex As Exception
End Try
End Sub
on form load i am calling both sub:
loadProductList()
UpdatePurchaseItemList() ' this does not update any thing
but when i call this sub on button click even it works perfectly.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
UpdatePurchaseItemList() 'it shows the updates.
End Sub
please tell me why it does not show updates?
Thanks
I'm not able to test right now, but try endedit() after you update your datagridview:
With DataGridView1.Rows(i)
If .Cells("Code").Value = dbDataRead("PitemProductID") Then
.Cells("Qty").Value = dbDataRead("PitemProductQty")
.Cells("Price").Value = dbDataRead("PitemCost")
.Cells("Amount").Value = dbDataRead("PitemTotal")
DataGridView1.EndEdit()
Exit For
End If
End With
That should 'Commits and ends the edit operation on the current cell.' as per MSDN Datagridview.EndEdit Method
ok try this trick it will automatically update the data on you're datagridview
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RefreshData()
End Sub
Private Sub RefreshData()
Dim da As OleDbDataAdapter
Dim ds As New DataSet
If Not cnn.State = ConnectionState.Open Then
'open connection
cnn.Open()
End If
da = New OleDb.OleDbDataAdapter("Select * FROM tblPurchaseItems", cnn)
'Dim dt As New DataSet
'fill data to datatable
da.Fill(ds)
'offer data in data table into datagridview
Me.DataGridView1.DataSource = ds.Tables(0)
Me.DataGridView1.Refresh()
'close connection
cnn.Close()
End Sub
and then copy and paste RefreshData() before the end of your, add,edit,delete sub statement

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class