Datagridview Horizontal to vertical button - vb.net

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

Related

Edit cell on a DataGridView

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?

The record cannot be deleted or changed because table 'Modules' includes related records

Having a problem with deleting records this exception keeps occurring.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: The record cannot be deleted or changed because table 'Modules' includes related records.
Public Class frmStudentDatabase
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=StudentDatabase.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * From Students", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDataSet As New DataSet()
Dim objModuleDA As New OleDb.OleDbDataAdapter("Select * From Modules", objConnection)
Dim objModuleCB As New OleDb.OleDbCommandBuilder(objModuleDA)
Private Sub frmStudentDatabase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Call the sub procedure that will fill the dataset
'Create (Relationships) and Retrieve all Student_ID numbers
Retrieve()
End Sub
Private Sub cboStudents_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboStudents.SelectedIndexChanged
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub Retrieve()
objDataSet.Clear()
objStudentDA.FillSchema(objDataSet, SchemaType.Source, "Students")
objStudentDA.Fill(objDataSet, "Students")
objModuleDA.FillSchema(objDataSet, SchemaType.Source, "Modules")
objModuleDA.Fill(objDataSet, "Modules")
objDataSet.Relations.Clear()
objDataSet.Relations.Add("Students2Modules", objDataSet.Tables("Students").Columns("Student_ID"), _
objDataSet.Tables("Modules").Columns("Student_ID"))
'Empty combo box
cboStudents.Items.Clear()
'Loop through each row, adding the Student_ID to the combobox
Dim i As Integer, strCurrentID As String
For i = 1 To objDataSet.Tables("Students").Rows.Count
strCurrentID = objDataSet.Tables("Students").Rows(i - 1).Item("Student_ID")
cboStudents.Items.Add(strCurrentID)
Next
'Select first item in the list
cboStudents.SelectedIndex = 0
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub FillStudentDetails()
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem)
txtStudentID.Text = objRow.Item("Student_ID")
txtStudentName.Text = objRow.Item("Student_Name")
txtStudentAddress.Text = objRow.Item("Student_Address")
End Sub
Public Sub FillModuleDetails()
Dim objStudent As DataRow, objModule As DataRow
Dim strModuleEntry As String
'Clear any existing modules
lstModules.Items.Clear()
'Find the current student record
objStudent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
For Each objModule In objStudent.GetChildRows("Students2Modules")
strModuleEntry = objModule.Item("Module_ID") & "," & objModule.Item("Module_Name") &
"," & objModule.Item("Module_Desc")
lstModules.Items.Add(strModuleEntry)
DataGridView1.DataSource = objDataSet.Tables("Modules")
Next
End Sub
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
Dim objRow As DataRow
Dim objRowModules As DataRow
Dim RowIndex As Integer
objRow = objDataSet.Tables("Students").NewRow
objRow.Item("Student_Name") = InputBox("Please Enter Student Name:")
objRow.Item("Student_Address") = InputBox("Please Enter Student Address:")
'Add data row to table
objDataSet.Tables("Students").Rows.Add(objRow)
objStudentDA.Update(objDataSet, "Students")
'Set up the module data row object
objRowModules = objDataSet.Tables("Modules").NewRow
'Find the number of the last row
RowIndex = objDataSet.Tables("Students").Rows.Count - 1
'Tell vb.net to get the Student_ID value from the last row
objRowModules.Item("Student_ID") = objDataSet.Tables("Students").Rows(RowIndex)("Student_ID")
objRowModules.Item("Module_Name") = InputBox("Please Enter Module Name:")
objRowModules.Item("Module_Desc") = InputBox("Please Enter Module Description:")
'Add to the DB
objDataSet.Tables("Modules").Rows.Add(objRowModules)
'Update the data adapter
objModuleDA.Update(objDataSet, "Modules")
MessageBox.Show("New record saved", "Saved")
Retrieve()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'Code to modify an existing record
Dim objRowCurrent As DataRow
objRowCurrent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
'We cannot modify the ID as it is an AutoNumber
objRowCurrent("Student_Name") = txtStudentName.Text
objRowCurrent("Student_Address") = txtStudentAddress.Text
objStudentDA.Update(objDataSet, "Students")
objDataSet.AcceptChanges()
'Now that we made changes, we need to retrieve the new data
Retrieve()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Dim i As integer, strCurrentID As String
Dim StudentName As String
Dim StudentFound As Boolean = False
StudentName = InputBox("Enter a Name Please!", "Search")
For i As Integer = 0 To (objDataSet.Tables("Students").Rows.Count - 1)
If CStr(objDataSet.Tables("Students").Rows(i)("Student_Name")) = StudentName Then
StudentFound = True
cboStudents.SelectedIndex = i
FillStudentDetails()
FillModuleDetails()
End If
Next
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex < objDataSet.Tables("Students").Rows.Count - 1) Then
rowIndex = rowIndex + 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "End")
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(txtStudentID.Text)
'Remember that all related child rows will be deleted! So no need to
'set up a new datarow for the Pet table
objRow.Delete()
objStudentDA.Update(objDataSet, "Students")
Retrieve()
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex > 0) Then
rowIndex = rowIndex - 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "Start")
End If
End Sub
End Class
You try to remove a record which has child records. Due to those references your removal fails. The reason is that the Student has Modules. You will need to remove the references to the Student before you can remove it.

Object reference error on chart load (Thread)

I am getting Object reference not set to an instance of an object error on chart creation with threads, It was running fine without threads but I have to do it with threads, please help
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
trd = New Thread(AddressOf ThreadTask)
trd.IsBackground = True
trd.Start()
End sub
Function
Private Sub ThreadTask()
Dim Data As String() = Functions.runAnalyticsReportSample(100278)
Functions.CredHolder(Session("User"), Session("Pw"))
Dim split As String() = {""}
Dim table As New DataTable()
Dim colB As DataColumn = table.Columns.Add("A", GetType(String))
Dim colD As DataColumn = table.Columns.Add("B", GetType(String))
For Each line In Data
split = line.Split(","c)
Dim row As DataRow = table.NewRow()
row.SetField(colB, split(0))
row.SetField(colD, split(1))
table.Rows.Add(row)
Next
'Chart1.Series.Add("test")
Chart1.Series("Series1").XValueMember = "A"
Chart1.Series("Series1").YValueMembers = "B"
Chart1.Series("Series1").IsValueShownAsLabel = True
Chart1.Series("Series1").IsVisibleInLegend = False
Chart1.DataSource = table
Chart1.DataBind()
End Sub

Auto-fill textbox on a dialog form, from a Datagridview on the original form, vb.net 2013

I am currently working in windows form applications using vb.net 2013. I have two forms, we can call them form1 and form 2 for now. Form1 has a datagridview with a checkbox column that the end user will click to open form2 as a dialog form. Once form2 opens I want it to automatically load and fill two text boxes that have information from corresponding columns from the original DGV. In short, the DGV on form1 has 3 columns; JobNumber, LineNumber, and the checkbox. The end user will click the checkbox to bring up form2 and I want the Jobnumber and Linenumber to automaticaly fill into two textboxes on form2. Here is my code from form1.
'assembly dialog result form
dr = f.ShowDialog
If dr = Windows.Forms.DialogResult.OK Then
'dim y as job string
Dim Y As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & Y & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Yes Then
'dim M as job string
Dim M As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & M & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Cancel Then
'refresh datagridview ordered
Call DGVOrderedRefresh()
End If
ElseIf e.ColumnIndex = 0 Then
'fail safe to make sure the header is not clicked
If e.RowIndex = -1 Then
Exit Sub
End If
The code for my dialog is as follows
Imports System.Data
Imports System.Data.SqlClient
Public Class BuildName
' Dim connstring As String = "DATA SOURCE = BNSigma\CORE; integrated security = true"
Dim connstring As String = "DATA SOURCE = BNSigma\TEST; integrated security = true"
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click
End Sub
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ds As New DataTable
Try
'load name combo box
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("SELECT Name FROM Production.dbo.FCNames", conn1)
Dim adapater As New SqlDataAdapter
adapater.SelectCommand = comm1
adapater.Fill(ds)
adapater.Dispose()
conn1.Close()
CBName.DataSource = ds
CBName.DisplayMember = "Name"
CBName.ValueMember = "Name"
End Using
End Using
Catch ex As Exception
MsgBox("Error loading name List, please contact a mfg. Engr.!")
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Update built by name
Dim v As Object = TBFloor.Text
Dim G As Object = TBLine.Text
Dim O As Object = TBJobNumber.Text
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET BuiltBy = #Name Where JobNumber = '" & O & "'", conn1)
comm1.Parameters.AddWithValue("#Name", CBName.Text)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Catch ex As Exception
MsgBox("Error updating Ordered table, please contact a MFG. ENGR.!")
MsgBox(ex.ToString)
End Try
End Sub
End Class
UPDATED CODE FOR VALTER
Form1 code
Public row_Index As Integer = 0
Private Sub DataGridOrdered_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridOrdered.CurrentCellDirtyStateChanged
If DataGridOrdered.IsCurrentCellDirty Then
DataGridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub DataGridOrdered_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridOrdered.CellValueChanged
If DataGridOrdered.Columns(e.ColumnIndex).Name = 9 Then
Dim checkCell As DataGridViewCheckBoxCell = CType(DataGridOrdered.Rows(e.RowIndex).Cells(9), DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
Form 2 code
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(3).Value
Dim value2 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(4).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
In your form1 add:
Public Row_Index As Integer = 0 //use a simple variable
Sub datagridOrdered_CurrentCellDirtyStateChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles datagridOrdered.CurrentCellDirtyStateChanged
If datagridOrdered.IsCurrentCellDirty Then
datagridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub datagridOrdered_CellValueChanged(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles datagridOrdered.CellValueChanged
If datagridOrdered.Columns(e.ColumnIndex).Name = "Assemble" Then //<- here
Dim checkCell As DataGridViewCheckBoxCell = _
CType(datagridOrdered.Rows(e.RowIndex).Cells(2), _ //<- here
DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
//RowIndex = e.RowIndex you dont need this
Row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
//Nor this
//Private _count As Integer
//Public Property RowIndex() As Integer
//Get
//Return _count
//End Get
//Set(value As Integer)
//_count = value
//End Set
//End Property
And in dialog load event use Form1.Row_Index instead:
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(0).Value //<- here
Dim value2 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(1).Value //<- here
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub
or add a module and add the Row_Index there. You can use it then as is
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(0).Value
Dim value2 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(1).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub

How to quit excel application from VB.NET

My program is able to retrieve data from an excel macro 2010 workbook and change contents and save changes made, all using the datagridview within VB.NET. However I'm facing a problem where the program saves but will not close. When I look at the processes in the task manager its still showing Excel 2010 as running. If anyone can help me find a way to quit this application I would greatly appreciate it!
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.IO
Public Class Form1
Dim SheetList As New ArrayList
Private excelObj As ExcelObject
Private dt As DataTable = Nothing
Dim DS As DataSet
Dim DS2 As DataSet
Dim ds3 As DataSet
Dim ds4 As DataSet
Dim ds5 As DataSet
Dim ds6 As DataSet
Dim ds7 As DataSet
Dim ds8 As DataSet
Dim ds9 As DataSet
Dim ds10 As DataSet
Dim ds11 As DataSet
Dim ds12 As DataSet
Dim ds13 As DataSet
Dim ds14 As DataSet
Dim ds15 As DataSet
Dim ds16 As DataSet
Dim ds17 As DataSet
Dim ds18 As DataSet
Dim MyCommand As OleDb.OleDbDataAdapter
Dim MyCommand2 As OleDb.OleDbDataAdapter
Dim MyCommand3 As OleDb.OleDbDataAdapter
Dim MyCommand4 As OleDb.OleDbDataAdapter
Dim MyCommand5 As OleDb.OleDbDataAdapter
Dim MyCommand6 As OleDb.OleDbDataAdapter
Dim MyCommand7 As OleDb.OleDbDataAdapter
Dim MyCommand8 As OleDb.OleDbDataAdapter
Dim MyCommand9 As OleDb.OleDbDataAdapter
Dim MyCommand10 As OleDb.OleDbDataAdapter
Dim MyCommand11 As OleDb.OleDbDataAdapter
Dim MyCommand12 As OleDb.OleDbDataAdapter
Dim MyCommand13 As OleDb.OleDbDataAdapter
Dim MyCommand14 As OleDb.OleDbDataAdapter
Dim MyCommand15 As OleDb.OleDbDataAdapter
Dim MyCommand16 As OleDb.OleDbDataAdapter
Dim MyCommand17 As OleDb.OleDbDataAdapter
Dim MyCommand18 As OleDb.OleDbDataAdapter
Dim objExcel As New Excel.Application()
Dim objWorkBook As Excel.Workbook = objExcel.Workbooks.Add
Dim objWorkSheet1 As Excel.Worksheet = objExcel.ActiveSheet
Dim objWorkSheet2 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet3 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet10 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet11 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet12 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet13 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet23 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet24 As Excel.Worksheet = objExcel.ActiveSheet
'<TBD make 15 more of these>
Dim MyConnection As OleDb.OleDbConnection
Dim MYDBConnection As DAO.Connection
Public MyWorkspace As DAO.Workspace
Public sizetable As DAO.Recordset
Public MyDatabase As DAO.Database
Public ReadOnly Property Excel() As ExcelObject
Get
If excelObj Is Nothing Then
excelObj = New ExcelObject(txtFilePath.Text)
End If
Return excelObj
End Get
End Property
Sub openExcelfile()
Dim dlg As New OpenFileDialog()
dlg.Filter = "Excel Macro Enabled Files|*.xlsm*|Excel Files|*.xls|Excel 2007 Files|*.xlsx|All Files|*.*"
If dlg.ShowDialog() = DialogResult.OK Then
excelObj = New ExcelObject(dlg.FileName)
txtFilePath.Text = dlg.FileName
btnRetrieve.Enabled = txtFilePath.Text.Length > 0
End If
Dim ExcelSheetName As String = ""
'open the excel workbook and create an object for it
objExcel = CreateObject("Excel.Application")
'do some exception handling on a blank txtfilepath.text
objWorkBook = objExcel.Workbooks.Open(txtFilePath.Text)
Dim i As Integer
i = 1
For Each objWorkSheets In objWorkBook.Worksheets
SheetList.Add(objWorkSheets.Name)
Select Case i
Case 4
objWorkSheet1 = objExcel.Worksheets(objWorkSheets.Name)
Case 5
objWorkSheet2 = objExcel.Worksheets(objWorkSheets.Name)
'ListBox1.Items.Add(objWorkSheets.Name)
'etc
End Select
i = i + 1
Next
End Sub
Sub Write2Excel()
Dim rowindex As Integer
Dim columnindex As Integer
For rowindex = 1 To DataGridView1.RowCount
For columnindex = 1 To DataGridView1.ColumnCount
objWorkSheet1.Cells(rowindex + 4, columnindex + 0) = DataGridView1(columnindex - 1, rowindex - 1).Value
Next
Next
'etc
End Sub
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
openExcelfile()
End Sub
Sub oldretrieve()
' Dim dt As DataTable = Me.Excel.GetSchema()
' cmbTableName.DataSource = (From dr In dt.AsEnumerable() Where Not dr("TABLE_NAME").ToString().EndsWith("$") Select dr("TABLE_NAME")).ToList()
' cmbTableName.Enabled = cmbTableName.Items.Count > 0
' btnGo.Enabled = cmbTableName.Items.Count > 0
' btnDrop.Enabled = cmbTableName.Items.Count > 0
End Sub
Sub RetrieveExcel()
'Create a connection to either 2007 and 2010 xls file
Dim fi As New FileInfo(txtFilePath.Text)
If fi.Extension.Equals(".xls") Then
MyConnection = New OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.8.0; " & "data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 8.0;")
ElseIf fi.Extension.Equals(".xlsx") Then
MyConnection = New OleDb.OleDbConnection( _
"provider=Microsoft.Ace.OLEDB.12.0; " & _
"data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 12.0;")
ElseIf fi.Extension.Equals(".xlsm") Then
MyConnection = New OleDb.OleDbConnection( _
"provider=Microsoft.Ace.OLEDB.12.0; " & _
"data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 12.0;")
End If
'First worksheet'
MyCommand = New OleDbDataAdapter("select * from [1- COTS Worksheet$A4:I150]", MyConnection)
'1- COTS Worksheet.Column(1).Locked = True
DS = New System.Data.DataSet()
MyCommand.Fill(DS)
'---This will prevent the user from editing the size of the rows and columns of the datagrid---'
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.AllowUserToResizeRows = False
DataGridView1.AllowUserToOrderColumns = False
DataGridView1.AllowUserToAddRows = False
DataGridView1.AllowUserToDeleteRows = False
DataGridView1.DataSource = DS.Tables(0).DefaultView
'---The following line makes the column read only---'
DataGridView1.Columns(5).ReadOnly = True
DataGridView1.Columns(6).ReadOnly = True
'''''''if the column is editible then the foreground = blue ''''''''
DataGridView1.Columns(0).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(1).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(2).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(3).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(4).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(7).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(8).DefaultCellStyle.ForeColor = Color.Blue
' ''''''This will get rid of the selection blue color for the cells''''''''''''''''''''
DataGridView1.DefaultCellStyle.SelectionBackColor = DataGridView1.DefaultCellStyle.BackColor
DataGridView1.DefaultCellStyle.SelectionForeColor = DataGridView1.DefaultCellStyle.ForeColor
'TABLE TO WRITE TO -
'FIELD TO WRITE TO -
End Sub
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Try
Cursor.Current = Cursors.WaitCursor
RetrieveExcel()
Finally
Cursor.Current = Cursors.Default
End Try
End Sub
Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' btnRetrieve.Enabled = True
MyWorkspace = DAODBEngine_definst.Workspaces(0)
End Sub
Private Sub txtFilePath_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFilePath.TextChanged
btnRetrieve.Enabled = System.IO.File.Exists(txtFilePath.Text)
End Sub
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
If Me.excelObj IsNot Nothing Then
Me.excelObj.Dispose()
End If
closexlsfile()
End Sub
Private Sub DBFilePath_TextChanged(sender As Object, e As EventArgs) Handles DBFilePath.TextChanged
End Sub
Private Sub BtnBrowseDB_Click(sender As Object, e As EventArgs) Handles BtnBrowseDB.Click
opendbfile()
End Sub
Function opendbfile() As Boolean
Dim dlg As New OpenFileDialog()
dlg.Filter = "DB files|*.mdb|Access DB files|*.accdb|All Files|*.*"
If dlg.ShowDialog() = DialogResult.OK Then
DBFilePath.Text = dlg.FileName
'temporarily myfile will be set to c:/Exceltest/template.mdb
' myfile = "c:/Exceltest/template.mdb"
Try
If DBFilePath.Text <> "" Then
'On Error GoTo errorhandler
MYDBConnection = MyWorkspace.OpenConnection("provider=Microsoft.Ace.OLEDB.12.0; " & "data source=" & txtFilePath.Text)
MyDatabase = MyWorkspace.OpenDatabase(DBFilePath.Text)
sizetable = MyDatabase.OpenRecordset("size", DAO.RecordsetTypeEnum.dbOpenTable)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Function
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
'---This Try Finally block with set current cursor to waiting cursor while the program write to excel---'
Try
Cursor.Current = Cursors.WaitCursor
Write2Excel()
Finally
Cursor.Current = Cursors.Default
End Try
End Sub
Sub closexlsfile()
Try
''Do we need to save the file first?
objWorkBook.Save()
objWorkBook.Close()
objExcel.Quit()
'something weird happening on this line
MyConnection.Close()
MyConnection.Dispose()
objWorkBook = Nothing
objExcel = Nothing
Catch
End Try
'TBD the other objworksheets get closed here
End Sub
Private Sub closexls_Click(sender As Object, e As EventArgs) Handles closexls.Click
closexlsfile()
NAR(objWorkSheet1)
NAR(objWorkSheet2)
NAR(objworksheet3)
NAR(objworksheet10)
NAR(objworksheet11)
NAR(objworksheet12)
NAR(objworksheet13)
NAR(objworksheet23)
NAR(objworksheet24)
objWorkBook.Close(False)
NAR(objWorkBook)
NAR(MyConnection)
objExcel.Quit()
NAR(objExcel)
Debug.WriteLine("Sleeping...")
System.Threading.Thread.Sleep(5000)
Debug.WriteLine("End Excel")
End Sub
'---This is a method that I found of MSDN to quit an office application but it doesn't seem to work---'
Private Sub NAR(ByVal obj As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 0)
End While
Catch
Finally
obj = Nothing
End Try
End Sub
End Class
You obviously have a lot of code and I can't go through all of that. However I dealt with this problem in the past. It is usually due to an unreleased object of some kind. For example lots of code samples from the intertubes suggests that you do things like
objWorkBook = objExcel.Workbooks.Open(txtFilePath.Text)
This is potentially dangerous, you should never have more than ONE . in a single right hand value. Instead go for something like
Workbooks wrkbks = objExcel.Workbooks
objWorkBook = wrkbks.Open(txtFilePath.Text)
Otherwise there will be memory allocated for the WorkBooks that isn't explicitly released. This is really a pain to go through all your code base once you've discovered this, but it solved the problem for me.
Your NAR sub should have it handled, but I far prefer Marshal.FinalReleaseComObject method - no loop required. You need to make sure all instances have been addressed - like in the closexlsfile() method you do not call NAR for these Com objects. I suggest some code cleanup.