I am trying to make a quiz that reads from a random file, checks the answer then picks a new question. I am having trouble because when I click the button to check the answer it checks it against the next question instead of the current. I think this has something to do with opening the next question before checking. I am only fairly new to Visual Basic and coding in general so any help will be appreciated.
Here is the code giving me the trouble.(Sorry for the big chunk of Code)
Private Sub btn_next_Click(sender As Object, e As EventArgs) Handles btn_next.Click
ProgressBar1.Increment(1)
'Selects Random Number and Puts it into var_qnum
Dim curNumber As Integer
If (alreadyPicked.Count < var_amount) Then
Dim rand As Random = New Random
Do
curNumber = rand.Next(0, var_amount)
Loop While (alreadyPicked.Contains(curNumber))
End If
If (curNumber >= 0 AndAlso Not alreadyPicked.Contains(curNumber)) Then
alreadyPicked.Add(curNumber)
var_qnum = curNumber
var_filepath = "\questions\" + var_qnum.ToString + ".txt"
Else
End If
'Defines var_row stuff
Dim var_row As Integer = 0
Dim var_question As String
Dim var_type As String
Dim var_answer As String
Dim var_opta As String
Dim var_optb As String
Dim var_optc As String
Dim var_optd As String
'Opens the file corresponding to var_qnum
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
Application.StartupPath & var_filepath)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters("|")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
var_row += 1
If var_row = 1 Then
var_question = currentField
ElseIf var_row = 2 Then
var_type = currentField
ElseIf var_row = 3 Then
var_opta = currentField
ElseIf var_row = 4 Then
var_optb = currentField
ElseIf var_row = 5 Then
var_optc = currentField
ElseIf var_row = 6 Then
var_optd = currentField
ElseIf var_row = 7 Then
var_answer = currentField
var_row = 0
ElseIf var_row = 3 And var_type = "Close" Then
var_answer = currentField
var_row = 0
End If
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"Is Not valid And will be skipped.")
End Try
End While
End Using
lbl_type.Text = var_type
If var_type = "Multiple Choice" Then
rb_a.Visible = True
rb_b.Visible = True
rb_c.Visible = True
rb_d.Visible = True
rb_a.Text = var_opta
rb_b.Text = var_optb
rb_c.Text = var_optc
rb_d.Text = var_optd
End If
lbl_number.Text = var_qnum.ToString
txt_questionbox.Text = var_question
Dim var_check As String = "NULL"
If rb_a.Checked Then
var_check = "a"
ElseIf rb_b.Checked Then
var_check = "b"
ElseIf rb_c.Checked Then
var_check = "c"
ElseIf rb_d.Checked Then
var_check = "d"
End If
If var_check = var_answer Then
var_correct += 1
rb_a.Checked = False
rb_b.Checked = False
rb_c.Checked = False
rb_d.Checked = False
btn_next.Text = "Skip"
var_check = "NULL"
ElseIf var_check = "NULL" Then
var_skip += 1
ElseIf var_check <> var_answer Then
var_incorrect += 1
rb_a.Checked = False
rb_b.Checked = False
rb_c.Checked = False
rb_d.Checked = False
btn_next.Text = "Skip"
var_check = "NULL"
Else
MsgBox("Error")
End If
If var_correct + var_incorrect + var_skip = var_amount Then
Me.Visible = False
Form3.Visible = True
End If
End Sub
Related
Scenario
I have a word document where I have a table as shown in Image 1. The checkboxes are used to show the next contents. For example, I have in first step yes and no, when yes is checked the next content is shown. And in next step, I have thre Checkboxes with case 1,2 and 3 respectively.
When the case 1 is checked I have next a text that is filled via vba as F1Feld1...till F4Feld1.
Problem
First problem is, I am unable to create a function where only yes and no can be checked as well as either of the case can be checked. Second, problem is that the vba for case checkboxes run perfectly when I have them created separate but when combined together only case 1 vba runs.
Following is my code:
Option Explicit
Dim tabelle As Table, zelle As Cell
Private Sub Document_ContentControlOnEnter(ByVal CC As ContentControl)
Dim r As Range
Set tabelle = ActiveDocument.Bookmarks("local").Range.Tables(1)
If ActiveDocument.SelectContentControlsByTag("Yes").Item(1).Checked = True Then
ActiveDocument.SelectContentControlsByTag("No").Item(1).Checked = False
Call local_blockiert
Else: Call local_offen
End If
If ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = True Then
On Error Resume Next
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F1Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F1Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F1Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F1Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = True Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F2Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F2Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F2Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F2Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = True Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F3Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F3Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F3Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F3Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
End If
End Sub
Private Sub local_blockiert()
Dim i As Long, j As Long
On Error GoTo fehler
With ActiveDocument.Bookmarks("local").Range
.Font.ColorIndex = wdWhite
End With
fehler:
Call AllesAuf
End Sub
Private Sub local_offen()
Dim i As Long, j As Long
On Error GoTo fehler
With ActiveDocument.Bookmarks("YesorNo").Range
.Font.ColorIndex = wdBlack
End With
fehler:
Call AllesAuf
End Sub
Private Sub yes_blockiert()
Dim j As Long
On Error GoTo fehler
With tabelle.Cell(2, 2)
.Shading.ForegroundPatternColorIndex = wdGray25
.Range.Font.ColorIndex = wdGray25
For j = 1 To .Range.ContentControls.Count
.Range.ContentControls(j).LockContents = True
Next j
End With
Exit Sub
fehler:
Call AllesAuf
End Sub
Private Sub yes_offen()
Dim j As Long
On Error GoTo fehler
With tabelle.Cell(2, 2)
For j = 1 To .Range.ContentControls.Count
.Range.ContentControls(j).LockContents = False
Next j
.Shading.ForegroundPatternColor = RGB(255, 242, 204)
.Range.Font.ColorIndex = wdAuto
End With
Exit Sub
fehler:
Call AllesAuf
End Sub
Private Sub AllesAuf()
Dim i As Long
With ActiveDocument
For i = 1 To .ContentControls.Count
.ContentControls(i).LockContents = False
Next i
End With
End Sub
I'm generating an xls file from a datatable on a button click. Right now the path to save the file is hardcoded in the function to generate the file:
Function CreateExcelFile(xlFile As String) As Boolean
Try
Dim xlRow As Integer = 2
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
Dim xlWB = xlApp.Workbooks.Add
Dim xlWS = xlApp.Worksheets.Add
Dim intStr As Integer = 0
Dim NewFile As String = ""
Dim strCaption As String = "PSLF Driver Files Records"
xlFile = Replace(xlFile, "Return Files", "Reports")
xlFile = Replace(xlFile, "txt", "xlsx")
xlFile = Replace(xlFile, "_", " ")
intStr = InStr(xlFile, "Reports")
xlApp.IgnoreRemoteRequests = True
xlWS = xlWB.Worksheets(xlApp.ActiveSheet.Name)
xlApp.DisplayAlerts = False
xlApp.Sheets.Add()
Dim xlTopRow As Integer = 2 'First Row to enter data
xlApp.Sheets.Add()
xlApp.Sheets(1).Name = strCaption
xlApp.Sheets(1).Select()
'Store datatable in 2-dimensional array
Dim arrExcel(frm_Records.BindingSource1.DataSource.Rows.Count, frm_Records.BindingSource1.DataSource.Columns.Count - 1) As String
'Write header row to array
arrExcel(0, 0) = "SSN"
arrExcel(0, 1) = "CREATE_DATE"
arrExcel(0, 2) = "SERVICER_CODE"
arrExcel(0, 3) = "STATUS"
arrExcel(0, 4) = "DRIVER_FILE_OUT"
arrExcel(0, 5) = "LAST_UPDATE_USER"
arrExcel(0, 6) = "LAST_UPDATE_DATE"
arrExcel(0, 7) = "CREATE_USER"
'Copy rows from datatable to array
xlRow = 1
For Each dr As DataRow In frm_Records.BindingSource1.DataSource.Rows
arrExcel(xlRow, 0) = dr("SSN")
arrExcel(xlRow, 1) = dr("CREATE_DATE")
arrExcel(xlRow, 2) = dr("SERVICER_CODE")
arrExcel(xlRow, 3) = dr("STATUS")
If IsDBNull(dr("DRIVER_FILE_OUT")) Then
arrExcel(xlRow, 4) = ""
Else
arrExcel(xlRow, 4) = dr("DRIVER_FILE_OUT")
End If
arrExcel(xlRow, 5) = dr("LAST_UPDATE_USER")
arrExcel(xlRow, 6) = dr("LAST_UPDATE_DATE")
arrExcel(xlRow, 7) = dr("CREATE_USER")
xlRow += 1
Next
'Set up range
Dim c1 As Microsoft.Office.Interop.Excel.Range = xlApp.Range("A1") 'Top left of data
Dim c2 As Microsoft.Office.Interop.Excel.Range = xlApp.Range("T" & frm_Records.BindingSource1.DataSource.Rows.Count - 1 + xlTopRow) 'Bottom right of data
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlApp.Range(c1, c2)
xlRange.Value = arrExcel 'Write array to range in Excel
xlWB.ActiveSheet.Range("A:T").Columns.Autofit()
xlWB.ActiveSheet.Range("A1:T1").Interior.Color = RGB(255, 255, 153)
xlWB.ActiveSheet.Range("A1:T1").Font.Bold = True
With xlApp.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
xlApp.ActiveWindow.FreezePanes = True
Dim strSheet As String
For Each Sht In xlWB.Worksheets
If Sht.name Like "*Sheet*" Then
strSheet = Sht.name
xlApp.Sheets(strSheet).delete()
End If
Next
xlApp.IgnoreRemoteRequests = False
xlWB.SaveAs(xlFile)
xlWB.Close()
Dim xlHWND As Integer = xlApp.Hwnd
'this will have the process ID after call to GetWindowThreadProcessId
Dim ProcIdXL As Integer = 0
'get the process ID
GetWindowThreadProcessId(xlHWND, ProcIdXL)
'get the process
Dim xproc As Process = Process.GetProcessById(ProcIdXL)
xlApp.Quit()
'Release
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
'set to nothing
xlApp = Nothing
'kill it with glee
If Not xproc.HasExited Then
xproc.Kill()
End If
Catch ex As Exception
WP.WAPC_RUNSCRIPT_ERROR_FILE(WP.argScriptName, "Error Writing to Excel Report: " & ex.Message)
Return False
End Try
Return True
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Private Function GetWindowThreadProcessId(ByVal hwnd As IntPtr, _
ByRef lpdwProcessId As Integer) As Integer
End Function
#End Region
What I want to do is upon completion of the creation of the Excel file, I want to give the user the option of where to save the newly created file. I'm new at
Winforms and am not sure how to do this.
What is the best way to enable the user to choose where to saved the file?
Update:
Working code after #Claudius' answer.
Private Sub btnRecExport_Click(sender As Object, e As EventArgs) Handles
btnRecExport.Click
Dim file As String = "I:\PSLFRecords.xlsx"
CreateExcelFile(file)
Dim sfdRecords As New SaveFileDialog()
sfdRecords.Filter = "Excel File|*.xls"
sfdRecords.Title = "Save PSLF Driver Records"
sfdRecords.ShowDialog()
If sfdRecords.FileName <> "" Then
xlWB.SaveAs(sfdRecords.FileName)
fs.Close()
End If
End Sub
From MSDN edited to your needs:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
' Displays a SaveFileDialog so the user can save the Image
' assigned to Button2.
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel File|*.xls
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
' If the file name is not an empty string open it for saving.
If saveFileDialog1.FileName <> "" Then
xlWB.SaveAs(saveFileDialog1.FileName)
fs.Close()
End If
End Sub
All you'd actually need is just a new instance of the FolderBrowserDialog Class, that will return to you the path the user selected. All the information you need is already present in the documentation.
I can not get this to work. I am trying to populate column 2 with values from txt file and to skip cells that has no value in column 1 but without skipping data from text file.
This is what I get :
And code that I'm using :
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i).Cells(1).Value Is Nothing Then
'MsgBox(DataGridView1.Rows(i).Index)
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.WhiteSmoke
Else
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i).Cells(2).Value = LBS001(0)
Next
End If
Next
In code above line If DataGridView1.Rows(i).Cells(1).Value Is Nothing is not working. When that line is replaced with this one If DataGridView1.Rows(i).Cells(1).Value = "", I get this :
Here A201A is missing and for every empty row in column1 1 result is going to be skipped.
How to populate column 2 with data from txt file so that only rows are skipped not results.
EDIT :
I've tried something else and it works for the first empty cell in column 2, but when it comes to a second...it skips one data from array and then continues normally until reaches another empty cell. Example : A201A...A224A (everything OK)...blank cell(skipped)...A205 in OK but in 206 cell it puts A207A.
Now, this code below works too, thanks to Steve.
Dim Dat2() As String = Split(start1(0), Environment.NewLine)
Dim Dat2A() As String = Split(Dat2(0), ";")
Dim Dat2B() As String = Split(Dat2(1), ";")
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
Dim a As Integer = 0
For x As Integer = 0 To DataGridView1.Rows.Count - 2
If DataGridView1.Rows(x).Cells(1).Value <> "" Then
DataGridView1.Rows(x).Cells(2).Value = Dat2(a)
a += 1
Else
DataGridView1.Rows(x).Cells(2).Value = ""
End If
End If
Next
EDIT 2 :
Thanks to Steve...I've changed code a bit and it works. Only problem is I am missing two lines in lineCount I think because of every DGV row that is skipped.
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
MsgBox(lineCount)
Dim i2 As Integer = 0
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i2).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i).Cells(1).Value <> "" Then
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i).Cells(2).Value = LBS001(0)
Next
i2 += 1
Else
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.WhiteSmoke
End If
Next
What you are doing now is using i to read the line and i to write to your grid. What you need is another variable like i2 that you increment manually when you set the value in a grid, or need to skip a line in the grid.
Dim i2 as Int32 = 0
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i2).Cells(1).Value Is Nothing Then
'MsgBox(DataGridView1.Rows(i2).Index)
DataGridView1.Rows(i2).DefaultCellStyle.BackColor = Color.WhiteSmoke
Else
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i2).Cells(2).Value = LBS001(0)
Next
i2 += 1
End If
Next
EDIT: After further review and edits by the OP, this is a better answer:
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lines() = System.IO.File.ReadAllLines(fileName)
Dim lineCount = lines.Length
Dim a As Integer = 0
For x As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(x).Cells(1).Value <> "" Then
DataGridView1.Rows(x).Cells(2).Value = lines(a)
a += 1
Else
DataGridView1.Rows(x).Cells(2).Value = ""
End If
Next
I have a DataGrid control that fills with a data set.
I don't show all fields of data set in DataGrid control.
I want to create an excel file from my DataGrid.
How to get solution?
(windows form , vb net 1.1)
Try this
Link
OR
Try This
Imports Excel = Microsoft.Office.Interop.Excel
Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("sheet1")
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "NameYourSheet"
End With
For i = 0 To DataGrid1.RowCount - 1
For j = 0 To DataGrid1.ColumnCount - 1
wSheet.Cells(i + 1, j + 1).value = DataGrid1.Rows(i).Cells(j).Value.tosring
Next j
Next i
wSheet.Columns.AutoFit()
Private Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
Dim xlApp As Excel.Application = New Excel.Application
xlApp.SheetsInNewWorkbook = 1
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Worksheets.Item(1)
xlWorkSheet.Name = "Example_Export"
For nRow = 0 To dgvDataToExport.Rows.Count - 1
For nCol = 0 To dgvDataToExport.Columns.Count - 1
xlWorkSheet.Cells(nRow + 1, nCol + 1) = dgvDataToExport.Rows(nRow).Cells(nCol).Value
Next nCol
Next nRow
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs("C:\Example.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges)
xlWorkBook.Close()
xlApp.Quit()
End Sub
Try with this one:
Sub create_excel(sender As Object, e As EventArgs)
Dim strFileName As string
Dim tw As New StringWriter()
Dim hw As New HtmlTextWriter(tw)
strFileName = "some_excel_from_datagrid.xls"
Response.ContentType = "application/vnd.msexcel"
Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName)
Response.Charset = "UTF-8"
Response.ContentEncoding = Encoding.Default
DataGridID.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
End Sub
Maybe in this princip work.
String path = #"D:\users\....";
//your path
String connStr = "Provider=//your provider;Data Source=" + path + ";Extended Properties=Excel 12.0;";
//The connection to that file
OleDbConnection conn = new OleDbConnection(connStr);
//The query
string strSQL = "SELECT * FROM [?]";
//The command
OleDbCommand cmd = new OleDbCommand(/*The query*/strSQL, /*The connection*/conn);
DataTable dT = new DataTable();
conn.Open();
try
{
OleDbDataReader dR = cmd.ExecuteReader();
dT.Load(dR);
bS.DataSource = dT;
dGV.DataSource = bS;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Try
If Not dgv.RowCount = 0 Then
Dim folderBrowser As New FolderBrowserDialog
folderBrowser.Description = "Select location to save the report"
Dim filepath1 As String = ""
If (folderBrowser.ShowDialog() = DialogResult.OK) Then
filepath1 = folderBrowser.SelectedPath
Else
Exit Sub
End If
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Try
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim titleStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle1")
titleStyle.Font.Bold = True
titleStyle.Font.Size = "18"
titleStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
xlWorkSheet.Cells(2, 2) = "Employee Payment Report"
xlWorkSheet.Cells(2, 4) = DateAndTime.Now.ToString("dd/MM/yyyy")
xlWorkSheet.Cells(2, 2).Style = "NewStyle1"
xlWorkSheet.Cells(2, 4).Style = "NewStyle1"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'======================================================================================================
Dim headerStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
headerStyle.Font.Bold = True
headerStyle.Font.Size = "12"
headerStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Brown)
For k = 1 To dgv.Columns.Count
xlWorkSheet.Cells(4, k) = dgv.Columns(k - 1).HeaderText
xlWorkSheet.Cells(4, k).Style = "NewStyle"
Next
'=======================================================================================================
Dim str As String = ""
Dim l As Integer = 1
j = 6
Dim amt As Double = 0.0
For i = 0 To dgv.RowCount - 1
amt = amt + dgv.Rows(i).Cells(4).Value
For m = 0 To dgv.ColumnCount - 1
xlWorkSheet.Cells(j, l) = dgv(m, i).Value.ToString()
str = dgv(m, i).Value.ToString()
l = l + 1
Next
j = j + 1
l = 1
Next
'======================================================================================================
Dim lastStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle2")
lastStyle.Font.Bold = True
lastStyle.Font.Size = "12"
lastStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
Dim c As Integer = dgv.ColumnCount
xlWorkSheet.Cells(j + 2, c - 1) = "Total Amount"
xlWorkSheet.Cells(j + 2, c) = amt.ToString
xlWorkSheet.Cells(j + 2, c - 1).Style = "NewStyle2"
xlWorkSheet.Cells(j + 2, c).Style = "NewStyle2"
'=======================================================================================================
xlWorkSheet.SaveAs(filepath1 + "\EmployeePaymentReport.xlsx")
xlWorkBook.Close()
xlApp.Quit()
cls.releaseObject(xlApp)
cls.releaseObject(xlWorkBook)
cls.releaseObject(xlWorkSheet)
MsgBox("You can find the file at " + filepath1 + "\EmployeePaymentReport.xlsx")
Catch ex As Exception
MsgBox(ex.Message)
For Each Process In System.Diagnostics.Process.GetProcessesByName("EXCEL")
If Process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE") Then
Process.Kill()
End If
Next
End Try
Else
Exit Sub
End If
Catch ex As Exception
End Try
End Sub
I am triying to use background worker for my data which process 1k+ records and update them to the excel sheet. So I thought of using the background worker and the background worker gets hit but coming out of it and triggering the background work completed event without performing its action.
Below is my code:
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
ProgressBar1.Maximum = 100
ProgressBar1.Step = 1
ProgressBar1.Value = 0
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If cmbAccounts.SelectedIndex = 0 Then
Dim Input1 As String = Directory.GetCurrentDirectory & "\Samples\abc.xlsx"
Dim tdate As String = Me.PresentDate.Value.ToString("yyyy-MM-dd")
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 123)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView1.DataSource = myDataSet.Tables(0)
Me.DataGridView2.DataSource = myDataSet.Tables(1)
Me.DataGridView3.DataSource = myDataSet.Tables(2)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input1)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
Dim SecondTableFirstRow As Integer = EndOfFirstTable + 1
For i = 1 To myDataSet.Tables(1).Rows.Count
For j = 0 To myDataSet.Tables(1).Columns.Count - 1
xlApp.Cells(i + SecondTableFirstRow, j + 1) = _
myDataSet.Tables(1).Rows(i - 1)(j).ToString()
Next
Next
EndOfSecondTable = myDataSet.Tables(1).Rows.Count + 1
Dim ThirdTableFirstRow As Integer = EndOfSecondTable + 1
For i = 1 To myDataSet.Tables(2).Rows.Count
For j = 0 To myDataSet.Tables(2).Columns.Count - 1
xlApp.Cells(i + ThirdTableFirstRow, j + 1) = _
myDataSet.Tables(2).Rows(i - 1)(j).ToString()
Next
Next
EndOfThirdTable = myDataSet.Tables(2).Rows.Count + 1
If DataGridView1.Rows.Count - 1 + DataGridView2.Rows.Count - 1 + DataGridView3.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1)
'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblChargeEntry.Text = DataGridView1.RowCount - 1 + DataGridView2.RowCount - 1 + DataGridView3.RowCount - 1
value1 = lblChargeEntry.Text
Dim _
Destinationpath As String = Directory.GetCurrentDirectory & "\Output\abc_" & tdate & ".xlsx"
xlApp.ActiveWorkbook.SaveAs(Destinationpath)
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
End Using
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
Dim Input2 As String = Directory.GetCurrentDirectory & "\Samples\bbc.xls"
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 234)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView4.DataSource = myDataSet.Tables(0)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input2)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
Try
Dim EndOfFirstTable As Integer
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
If DataGridView4.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Catch
End Try
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1)
'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblPaymentPosting.Text = DataGridView4.RowCount - 1
value2 = lblPaymentPosting.Text
Dim _
Destinationpath As String = Directory.GetCurrentDirectory & _
"\Output\bbc_" & tdate & ".xls"
xlApp.ActiveWorkbook.SaveAs(Destinationpath)
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
cmbAccounts.SelectedIndex = 1
End Using
End If
If cmbAccounts.SelectedIndex = 1 Then
Dim Input3 As String = Directory.GetCurrentDirectory & "\Samples\123.xlsx"
Dim tdate As String = Me.PresentDate.Value.ToString("yyyy-MM-dd")
Using myConnection As New SqlConnection("Data Source=mydatasource;Initial Catalog=db0XXX;Persist Security Info=True;User ID=sa;Password=abcd"), myCommand As New SqlCommand("GetLog", myConnection), adapter As New SqlDataAdapter(myCommand)
myConnection.Open()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#AccountID", 234)
myCommand.Parameters.AddWithValue("#Date", tdate)
' Create the DataAdapter
Dim myDataAdapter As New SqlDataAdapter(myCommand)
' Create the DataSet
Dim myDataSet As New DataSet
' Fill the DataSet
myDataAdapter.Fill(myDataSet)
Me.DataGridView1.DataSource = myDataSet.Tables(0)
Me.DataGridView2.DataSource = myDataSet.Tables(1)
Me.DataGridView3.DataSource = myDataSet.Tables(2)
' Close the connection
myConnection.Close()
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook = xlApp.Workbooks.Open(Input3)
xlWorkBook.Sheets(1).activate()
xlApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignCenter
xlApp.DisplayAlerts = False
xlApp.Columns.ColumnWidth = 25
For i = 1 To myDataSet.Tables(0).Rows.Count
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(i + 1, j + 1) = _
myDataSet.Tables(0).Rows(i - 1)(j).ToString()
Next
Next
EndOfFirstTable = myDataSet.Tables(0).Rows.Count + 1
Dim SecondTableFirstRow As Integer = EndOfFirstTable + 1
For i = 1 To myDataSet.Tables(1).Rows.Count
For j = 0 To myDataSet.Tables(1).Columns.Count - 1
xlApp.Cells(i + SecondTableFirstRow, j + 1) = _
myDataSet.Tables(1).Rows(i - 1)(j).ToString()
Next
Next
EndOfSecondTable = myDataSet.Tables(1).Rows.Count + 1
Dim ThirdTableFirstRow As Integer = EndOfSecondTable + 1
For i = 1 To myDataSet.Tables(2).Rows.Count
For j = 0 To myDataSet.Tables(2).Columns.Count - 1
xlApp.Cells(i + ThirdTableFirstRow, j + 1) = _
myDataSet.Tables(2).Rows(i - 1)(j).ToString()
Next
Next
If DataGridView1.Rows.Count - 1 + DataGridView2.Rows.Count - 1 + DataGridView3.Rows.Count - 1 = 0 Then
For i = 1 To 2
For j = 0 To myDataSet.Tables(0).Columns.Count - 1
xlApp.Cells(2, j + 1) = "NULL"
Next
Next
End If
xlApp.Columns.AutoFit()
Dim rSearchRange As Range
rSearchRange = xlWorkBook.Sheets(1).UsedRange.Columns(1) 'for example
If xlApp.WorksheetFunction.CountBlank(rSearchRange) Then
rSearchRange.SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete()
End If
lblChargeEntry.Text = DataGridView1.RowCount - 1 + DataGridView2.RowCount - 1 + DataGridView3.RowCount - 1
value3 = lblChargeEntry.Text
Dim Destinationpath As String = Directory.GetCurrentDirectory & "\Output\234_Log_" & tdate & ".xlsx"
xlApp.ActiveWorkbook.SaveAs(Destinationpath )
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
End Using
For j As Integer = 0 To 99999
Caluculate(j)
backgroundWorker.ReportProgress((j * 100) \ 100000)
Next
End If
End Sub
Private Sub Caluculate(i As Integer)
Dim pow As Double = Math.Pow(i, i)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
progressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
MsgBox("Reports created succesfully!")
End Sub
Try putting a try/catch around the if statement. That won't address the problem but should let you see the exception. You're running into a cross-threading UI access issue when accessing the ComboBox from within the thread.
See here: https://stackoverflow.com/a/5074467/264607
If you really want to access UI elements see here:
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.checkaccess.aspx