cgeier 187 Junior Poster

Also n % 2 is modulus division. Here, it only = 0 for mulitiples of 2.

Ex: 2, 4, 6, 8, 10, etc...

Modulus division is the remainder part of dividing two numbers.

ex:

5 / 2 = 2 remainder 1

so, 5 % 2 = 1

cgeier 187 Junior Poster

Is power connected to the hard drive? If so, you may consider using a power supply tester to ensure your power supply is functioning properly.

Here is a page stating that they are selling a 2 tb hdd pulled from a working Dell 760. Therefore, it must be possible to use a 2 tb drive in that model.

This is a genuine OEM Dell Optiplex 760 7200RPM hard drive. This hard drive was pulled from a working Dell Optiplex 760 computer and is guaranteed to work with all Dell Optiplex 760 computers.

Optiplex 760 and 3TB Hard Disk Windows 7

Beyond 2TB
Using a hard drive larger than 2.1TB on Windows-based computer systems may require special setup considerations

Beyond 2TB Video

cgeier 187 Junior Poster

What hard drive brand/model?

Which version of the Optiplex 760 do you have?

Here are the power specs:
OptiPlex 760 Desktop Tech Specs

Mini-Tower

305W Standard Power Supply; 255W 88% Efficient Power Supply, ENERGY STAR 5.0 compliant, Active PFC

Desktop

255W Standard Power Supply; 255W 88% Efficient Power Supply, ENERGY STAR 5.0 compliant, Active PFC

Small Form Factor

235W Standard Power Supply; 255W 88% Efficient Power Supply, ENERGY STAR 5.0 compliant, Active PFC

Ultra Small Form Factor

220W External PSU, ENERGY STAR 5.0 compliant.

The following article may be of interest:
Dell Optiplex 760 Upgrade Project

mouaadable commented: thank you +1
cgeier 187 Junior Poster

What brand/model of computer? Did you check the manufacturer's website for technical specs?

cgeier 187 Junior Poster

Looks like UPS has a program for software developers. Did you contact them?

UPS Developer Kit

UPS Developer Kit Community

UPS Developer Resource Center

UPS Ready Program

cgeier 187 Junior Poster

This documentation also provides some information on Maxicode (although it doesn't look like their product supports .NET).

cgeier 187 Junior Poster

Are you required to use InputBox? Not sure why you are using ListBox for those things.

  1. Prompt user for French marks (handle invalid entries)
  2. Prompt user for German marks (handle invalid entries)
  3. Prompt user for Spanish marks (handle invalid entries)
  4. Add marks to ListBox
  5. Calculate percentage mark
  6. Display result

Note: Re-check your calculation. Consider displaying your message using a Label, MessageBox, etc.

Consider using a ComboBox for each mark type and populate it with numbers 1-30.

Danny_7 commented: Hey, i was asked by a teacher to use a listbox, anyways is that the pseudocode then yea? +0
cgeier 187 Junior Poster

If the control is in a group box or panel, you need to search there for it. Think of it as searching for a file you stored in a directory "c:\temp". If you only search in "c:\" you won't find it, you need to look in "c:\temp". Likewise, group boxes and panels are containers.

cgeier 187 Junior Poster

You didn't copy the code correctly. Copy the code as is, line-by-line.

Check line #6:
BtnName = selectedBtn should be BtnName = selectedBtn.Name

Also, when renaming variables, rename all occurrences of the variable.

Pre-requisites:

  • Add 5 buttons to a form named "Form1.vb", name them as follows: A3, A4, A5, A6, A7

Form1.vb:
Note: I changed "sender.BackColor" to "selectedBtn.BackColor"--although either will work.

Public Class Form1

    Private BtnName As String = String.Empty

    Private Sub A3_Click(sender As System.Object, e As System.EventArgs) Handles A3.Click, A4.Click, A5.Click, A6.Click, A7.Click
        Dim selectedBtn As Button = sender

        If String.IsNullOrEmpty(BtnName) Then
            BtnName = selectedBtn.Name
            selectedBtn.BackColor = Color.Red
        Else If BtnName = selectedBtn.Name Then
            BtnName = String.Empty
            selectedBtn.BackColor = Control.DefaultBackColor
        Else
            'can only select 1 btn
            MsgBox("You can only select one seat for every Process")
        End If

    End Sub

End Class

Note: In this kind of scenario, one should probably be able to click on another button without having to de-select the previous one. Change the color on the previous button pressed back to the default color, and change the color of the newly pressed button to red.

cgeier 187 Junior Poster

I agree with others that other controls may be more appropriate. However, if you do need to use buttons, you can use the following:

Private BtnName As String = String.Empty

Private Sub A3_Click(sender As System.Object, e As System.EventArgs) Handles A3.Click, A4.Click, A5.Click, A6.Click, A7.Click
    Dim selectedBtn As Button = sender

    If String.IsNullOrEmpty(BtnName) Then
        BtnName = selectedBtn.Name
        sender.BackColor = Color.Red
    Else If BtnName = selectedBtn.Name Then
        BtnName = String.Empty
        sender.BackColor = Control.DefaultBackColor
    Else
        'can only select 1 btn
        MsgBox("You can only select one seat for every Process")
    End If

End Sub
cgeier 187 Junior Poster

What if a user wants to de-select a button and select another one? Keep track of the selected button name using a private string variable. If a button hasn't been selected or has been de-selected the value should be String.Empty. If a button is pressed and the variable = String.Empty then set variable = button name.

cgeier 187 Junior Poster

It sounds like the file you created isn't useful to you. Why don't you post the original file (or file format) and then explain what you are trying to accomplish.

cgeier 187 Junior Poster

What version of .NET are you using? What version of ReportViewer did you install?

cgeier 187 Junior Poster
cgeier 187 Junior Poster

What operating system? If Vista or newer (win 7, win 8), check that the user account control settings are the same on both computers.

Also, you might want see if a simple program (such as one that only opens a message box) runs on the other computer.

MessageBox.Show("Hello World")

Additionally, you can use the attached module "Module1.vb" to retrieve some additional computer information and compare the values on both computers.

To use it, just call "getInfo":

getInfo()
cgeier 187 Junior Poster

Reverend Jim is correct. This is C#, not VB.NET.

cgeier 187 Junior Poster

If you have VS Ultimate (2010 or newer), looks like you could add a "Modeling Project" to your solution. See the following:

How to: Create UML Modeling Projects and Diagrams

If this is for a class, you can use MS Visio or MS Word, or just draw it out on paper.

Object Modeling

Search for "Object Model"

Note: There are standards that have been defined. Shapes have a meaning (rectangle, elipse, line with arrow, etc...)

cgeier 187 Junior Poster

You've commented out the line that defines "@g" cmd.Parameters.AddWithValue... (ensure that the data type matches that of the data type in the database).

Also, in your insert, use parameterized queries.

cgeier 187 Junior Poster

Note: In WinPE, when in the command prompt window, you can type "exit" to reboot.

cgeier 187 Junior Poster

You can try the following:

Option 1:

  • Turn computer on. Press "F10" repeatedly (once or twice per second).
  • If prompted to "Edit Windows boot options...", press the escape key.
  • If the Windows Boot Manager screen appears ("Choose an operating system to start..."), select the OS you want to boot.

Note: If "F10" doesn't work, reboot and try another "F" key.

Option 2: Use "EasyBCD" as others have stated.

Option 3:

How to Manually Repair Windows 7 Boot Loader Problems

Option 4:
If you don't have the install DVD (or your install DVD doesn't have the "Repair your computer" option), you can create a bootable USB drive using WinPE 5.1 (it is for Win 8.1, but you should be able to use it for Win 7).

To create the bootable USB drive using Win 8 computer:

Demo 2: Installing Windows PE on a USB Drive

To create the bootable USB drive using Win 7 computer:

Download and install Windows Assessment and Deployment Kit (Windows ADK) for Windows 8.1 Update

  • Double-click "adksetup.exe".
  • You either choose Option A: "Install the Windows Assessment and Deployment Kit for Windows 8.1 to this computer" or Option B: "Download the Windows Assessment and Deployment Kit for Windows 8.1 for installation on a separate computer". (I chose Option B: "Download the Windows Assessment...", so I could save it and not have to download it again should I want to install it on another computer. If choosing Option B, …
mike_2000_17 commented: Nice complete explanation! +14
cgeier 187 Junior Poster

This is for C# but can be converted: C# send plain text to default printer (Zebra printer) http://stackoverflow.com/questions/19171628/c-sharp-send-plain-text-to-defult-printer-zebra-printer

cgeier 187 Junior Poster

You can't just return to MethodA. MethodA didn't call MethodD--MethodC did. Even with exceptions, if unhandled, they are passed back to the caller. An exception could potentially be passed from D to C to B to A. Also, control needs to be passed back from MethodD to MethodC so clean-up of MethodC can occur--disposing of objects. Why do you feel that you should avoid returning up the chain--from D to C to B to A?

strRusty_gal commented: Thanks =) +3
cgeier 187 Junior Poster

Add the following to the end of the script:

'====================================
'Loop through the files in the
'sub-folders in the path
'from above (objStartFolder)
'====================================

ShowSubFolders objFolder


Sub ShowSubFolders(Folder)
    On error resume next

    For Each Subfolder in Folder.SubFolders


        Set objFolder = objFSO.GetFolder(Subfolder.Path)
        Set colFiles = objFolder.Files

        For Each objFile in colFiles
            if (LCase(objFSO.getextensionname(objFile)) = "jpg") then
            oFile.Write objFolder & "\" & objFile.name & vbCrlf
            end if

        Next

        ShowSubFolders Subfolder
    Next
End Sub

So now you will have:

'====================================
'objStartFolder is where you enter 
'the folder path string
'====================================

objStartFolder = "C:\"
'objStartFolder = "C:\Users\user\Desktop\"
'objStartFolder = "C:\Temp\"

Wscript.Echo objStartFolder

'====================================
'create file system object
'====================================

set objFSO=CreateObject("Scripting.FileSystemObject")

'====================================
'outputFile is where you enter the 
'path and name of the LogFile text
'file.
'====================================

outputFile = "C:\Users\user\Desktop\LogFile.txt"


Set objFolder = objFSO.GetFolder(objStartFolder)
set oFile = objFSO.CreateTextFile(outputFile,True)

Set colFiles = objFolder.Files

'====================================
'Loop through the files in the path 
'from above (objStartFolder)
'====================================


For Each objFile in colFiles

    if (LCase(objFSO.getextensionname(objFile)) = "jpg") then
        oFile.Write objFolder & "\" & objFile.name & vbCrlf
    end if

Next

'====================================
'Loop through the files in the
'sub-folders in the path
'from above (objStartFolder)
'====================================

ShowSubFolders objFolder


Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders

        Set objFolder = objFSO.GetFolder(Subfolder.Path)
        Set colFiles = objFolder.Files

        For Each objFile in colFiles
            if (LCase(objFSO.getextensionname(objFile)) = "jpg") then
            oFile.Write objFolder & "\" & objFile.name & vbCrlf
            end if
        Next

        ShowSubFolders Subfolder
    Next
End Sub

How Can I Get a List of All the Files in a Folder and Its Subfolders?

Stuugie commented: Thank you so much for your assistance here +5
cgeier 187 Junior Poster

The reason for your error is because Mid throws an error if the value of start is < 1.

Mid Function

start: Character position in string at which the part to be taken begins.

InStrRev Function

Usage: InStrRev(string1, string2[, start[, compare]])

string1: Required. String expression being searched.

string2: Required. String expression being searched for.

...

InStrRev returns a value of 0 if string2 is not
found.

Stuugie commented: Thanks for clarifying why the MID Function errored out. +0
cgeier 187 Junior Poster

Try deleting the following code (lines 15-17):

if (LCase(Mid(objFile.Name, InstrRev(objFile.Name,"."))) = ".jpg") then
    oFile.Write objFolder & objFile.name & vbCrlf
end if

and replace it with this:

if (LCase(objFSO.getextensionname(objFile)) = "jpg") then
    oFile.Write objFolder & objFile.name & vbCrlf
end if

Resource:
VBScript: how do I determine file extensions?

The following may also be of interest:
Display All the Subfolders Within a Folder Using VBscript

Stuugie commented: Thanks for this help, I really appreciate it. +5
cgeier 187 Junior Poster

Two possibilities that I see:

Possibility 1: recNo.Length is only allowing 1 iteration (as others have stated)

Try outputing the value of k: MessageBox.Show("k: " + k);

Possibility 2:
Receiving error because SqlParameter(s) is/are already declared. This should produce an error. However, if one did the following (or some version of it):

Try

...code...

Catch ex as Exception

End Try

The error may not show--because exception handling was added but basically the exception was discarded (no code exists to handle the exception).

Solution to possibility 2:

With cmdUpdate
    .Parameters.AddWithValue("@status", "A")
    .Parameters.Add("@recno")
End With

For k = 0 To recno.Length - 1
    sqlUpdate = "UPDATE shipment SET status=@status WHERE recno=@recno"

    'for debugging purposes
    MessageBox.Show("k: " & k & " recno val: " & recno(k))

    With cmdUpdate
        .Parameters("@recno").Value = recno(k)

        .CommandText = sqlUpdate
        .Connection = conn
        .ExecuteNonQuery()
    End With
Next

Additionally, eliminate any discarded exceptions--ensure that some sort of error message is issued when an exception occurs.

cgeier 187 Junior Poster

You can try adding an application manifest to your project (as in UAC Troubles above).

Click "Project" (in menu bar)
Select "Add New Item"
Select "Application Manifest File"
Click "Add"

Try changing:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

To:

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

If that doesn't work, you may also look into changing "uIAccess" from false to true.

Step 6: Create and Embed an Application Manifest (UAC)

uiAccess Values:

False: The application does not need to drive input to the user interface of another window on the desktop. Applications that are not providing accessibility should set this flag to false. Applications that are required to drive input to other windows on the desktop (on-screen keyboard, for example) should set this value to true.

True: The application is allowed to bypass user interface control levels to drive input to higher privilege windows on the desktop. This setting should only be used for user interface Assistive Technology applications.

*Note: Applications with the uiAccess flag set to true must be Authenticode signed to start properly. In addition, the application must reside in a protected location in the file system. \Program Files\ and \windows\system32\ *

Also, \Program Files (x86)

And from:
Windows Integrity Mechanism Design

By specifying UIAccess=”true” in the requestedPrivileges attribute, the application is stating a requirement to bypass UIPI restrictions on sending window messages across privilege levels. Windows Vista implements the following policy checks before starting an application with UIAccess privilege.

• The …

cgeier 187 Junior Poster

Here are some more that may be of interest:

Inside Windows 7 User Account Control

Tools List for Understanding Windows Integrity Mechanism (WIM)

Windows Integrity Mechanism Design

-User Interface Privilege Isolation (UIPI) and integrity
-UIAccess for UI automation applications

Mandatory Integrity Control in Windows 7 | 8

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Are you running VS as an administrator? Try turning off UAC (under user accounts) before running your program and see if it works.

cgeier 187 Junior Poster

Open Sql Server Configuration Manager (for SQL Server 2008) and check that TCPIP is enabled.

Win 7:

  • Click Start
  • In "Search programs and files" textbox, type: SQLServerManager10.msc
  • Press "Enter"

Win 8:

  • In the search charm, under Apps type: SQLServerManager10.msc
  • Press "Enter"

Then,

  • Double-click "SQL Server Network Configuration"
  • Click "Protocols for SQLExpress" (where "SQLExpress" is the name of the instance that you are using)
  • Look at "TCP/IP". If disabled, right-click, and select "Enable". Then restart the MSSQL service (or reboot your computer).
cgeier 187 Junior Poster

You can try the following connection string:

public static string connectStr = @"Data Source='.\SQLExpress';Initial Catalog='DB1'; Integrated Security = True";

//public static string connectStr = string.Format("Data Source='.\\SQLExpress'; Initial Catalog=\'myDB\'; User Id=\'user1\'; Password=\'password\'");

//where .\SQLExpress2008 (serverName\DBInstanceName) 

//'Initial Catalog='database name'

//'Integrated Security=True' means that it uses Windows authentication 

SqlConnection connection = new SqlConnection(connectStr);
cgeier 187 Junior Poster
cgeier 187 Junior Poster

Your page margins are subject to the limitations of your printer. Check what the minimum margins are for your printer. Also ensure you've specified the correct paper size.

cgeier 187 Junior Poster

C# is case-sensitive. Are you sure your teacher didn't specify you to use "Base"? You can use "Base"--capital "B". Although, I wouldn't recommend using a different case of a reserved word. It would be similiar to you doing the following:

string employee = "John";
string Employee = "Bill";
string eMployee = "Joe";
string emPloyee = "Jane";

All would be permitted, but will likely lead to confusion either for you or for someone who has to maintain your code.

Perhaps part of the lesson to be learned from your assignment is about the case-sensitivity of C#.

cgeier 187 Junior Poster

I've never used ReportViewer, but I found this post:

set page layout for report viewer...

The following is converted and and adapted for VB .NET:

Dim myPageSettings As New System.Drawing.Printing.PageSettings()

myPageSettings.Margins =  New System.Drawing.Printing.Margins(0, 0, 0, 0)

Dim paperSize As System.Drawing.Printing.PaperSize = New System.Drawing.Printing.PaperSize()

'ToDo: update with the PaperKind 
'that your printer uses
paperSize.RawKind = System.Drawing.Printing.PaperKind.Letter

'paperSize.RawKind = System.Drawing.Printing.PaperKind.A4

myPageSettings.PaperSize = paperSize

'False for "Portrait"
'True for "Landscape"
myPageSettings.Landscape = False

Me.ReportViewer1.SetPageSettings(myPageSettings)

Me.ReportViewer1.RefreshReport()

However, it's untested, so not sure if it works or not.

cgeier 187 Junior Poster

Use a pen and paper and step through your code to see what is happening--to see what the computer sees.

cgeier 187 Junior Poster

If you aren't updating any data, you can use "ExecuteScalar" or "ExecuteReader".

ExecuteScalar returns a single value. It can be used when you only need to get a single column from a single row.

ExecuteReader returns rows in a DataReader. It can be used to retrieve data from multiple columns and multiple rows.

You don't need to retrieve the password from the database, but rather send the password that the user submitted and see if it matches the one in the database. You really shouldn't store clear text passwords though. You should encrypt it before storing it in the database. Then encrypt the password that the user submitted, and see if it matches the encrypted password in the database.

checkPassword:

Public Function checkPassword(ByVal username As String, ByVal password As String) As Boolean

    Dim totalRows As Integer = 0
    Dim passwordVerified As Boolean = False

    Try
        Using cn As New iDB2Connection(connectStr)
            Dim sqlText As String = String.Empty

            sqlText = "SELECT COUNT(*) FROM " + usersTbl + " "
            sqlText += "WHERE username = @username and password = @password"

            'open connection
            cn.Open()

            Using cmd As New iDB2Command(sqlText, cn)

                'add username parameter
                cmd.Parameters.AddWithValue("@username", username)

                'add password parameter
                cmd.Parameters.AddWithValue("@password", password)

                'execute the command
                'ExecuteScalar returns a single value / single column
                totalRows = Convert.ToInt32(cmd.ExecuteScalar())

                If totalRows >= 1 Then
                    passwordVerified = True
                End If

            End Using
        End Using

    Catch ex As iDB2Exception
        Throw New Exception("Error (checkPassword): " + ex.Message)

    Catch ex As Exception
        Throw New Exception("Error (checkPassword): " + ex.Message)

    End Try

    Return …
cgeier 187 Junior Poster

How many lines of code? Did you overstate your abilities during your interview? You may find it beneficial to shadow one (or more) of the users of the product--to get the end user experience. Aside from that, if you want to prove yourself, you will likely need to spend time at work as well as personal time to figure it all out.

cgeier 187 Junior Poster

In the second example it will skip the rest of the else if statements when it has found a satisfying condition. In your first example every if statement will be evaluated. In your short example it doesn't make much difference. The difference is noticed in a loop with many iterations or if you have many if statements or if your if statements must perform more complex (time consuming) evaluations. Of course this all depends on the frequency of a satisfying condition being found. The greatest benefit will result in the second example if you order the statements from most likely to occur to least likely to occur.

ddanbe commented: Great answer! +15
cgeier 187 Junior Poster

The following has been tested in Excel 2010:

Add a reference to Microsoft Excel xx.x Object Library

  • Project
  • Add Reference
  • COM
  • Microsoft Excel 14.0 Object Library

Create a new module named "Module1.vb".

Module1.vb:

Imports Excel = Microsoft.Office.Interop.Excel

Module Module1

    Public Enum ColumnVisibility
        Hide
        Show
    End Enum


    Public Sub setColumnVisibility(ByVal filename As String, ByVal visibility As ColumnVisibility)

        Dim xlApp As Excel.Application = New Excel.Application
        Dim xlWb As Excel.Workbook
        Dim xlPreviousActiveSheet As Excel.Worksheet
        Dim xlSheet As Excel.Worksheet
        Dim xlRng As Excel.Range

        'start Excel and get Application object
        xlApp = CreateObject("Excel.Application")

        'change to False if you don't
        'want Excel to be visible
        xlApp.Visible = True

        'open workbook
        xlWb = xlApp.Workbooks.Open(filename)

        'get previously active sheet
        'so we can make it the active sheet
        'again before we close the file
        xlPreviousActiveSheet = xlWb.ActiveSheet

        For i As Integer = 1 To xlWb.Sheets.Count

            xlSheet = xlApp.Sheets(i)

            'activate current sheet
            'needed for "Select"
            xlSheet.Activate()

            'get range of sheet
            xlRng = xlSheet.Cells()

            'Console.WriteLine("Total Rows: " & xlRng.Rows.Count)
            'Console.WriteLine("Total Columns: " & xlRng.Columns.Count)

            'select range
            xlSheet.Range(xlSheet.Cells(1, 10), xlSheet.Cells(xlRng.Rows.Count, xlRng.Columns.Count)).Select()

            If visibility = ColumnVisibility.Show Then
                'show columns in range
                xlApp.Selection.EntireColumn.Hidden = False
            Else
                'hide columns in range
                xlApp.Selection.EntireColumn.Hidden = True
            End If

            'undo selection
            xlApp.CutCopyMode = Excel.XlCutCopyMode.xlCopy
            xlSheet.Range("A1").Select()
        Next

        'make previous active sheet
        'the active sheet again
        'before we close the file
        xlPreviousActiveSheet.Activate()

        'close and save changes
        xlWb.Close(SaveChanges:=True)

        'quit Excel
        xlApp.Quit()

    End Sub

End Module  

Usage:

setColumnVisibility("C:\Temp\Book1.xlsx", ColumnVisibility.Hide)

Or

setColumnVisibility("C:\Temp\Book1.xlsx", ColumnVisibility.Show)

Resources:

VB.NET Excel

How to select cells/ranges by using …

cgeier 187 Junior Poster

I made a couple of changes to "ClsDB2", so I'm re-attaching it. Also attached below is the verion in VB .NET. Both are untested.

VB .NET version: ModuleDB2.zip

C# version: ClsDB2.zip

cgeier 187 Junior Poster

Below I've attached a C# version of the code so you can see how to do it in C#. The code is untested though, because I don't have a database to test it on.

I made the class static, so to use it, use <class name>.<method name>

ex: ClsDB2.doTasks()

Note: Change the namespace name to the name of the namespace for your project.

cgeier 187 Junior Poster

Also, when you are searching for information, do a general search rather than searching for info on DB2. You will get more results.

Example:

DB2: iDB2DataAdapter

Try searching for:

  • OleDbDataAdapter
  • SqlDataAdapter

DB2: iDB2Command

Try searching for:
SqlCommand
OleDbCommand

Basically, replace "iDB2" with "OleDb" or "Sql".

Here is some code I've adapted from this post.

doTasks:

Private Sub doTasks()
    Try
        Dim err As Exception = Nothing
        Dim dt As DataTable = Nothing

        'get data and put into a DataTable
        'if an exception occurs, it is 
        'returned in "err"
        dt = getData(err)

        If err IsNot Nothing Then
            MessageBox.Show("Error: " & err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            If dt IsNot Nothing Then
                showData(dt)
            Else
                MessageBox.Show("DataTable is Nothing.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
    Catch ex As Exception
        MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

getData:

Private Function getData(ByRef err As Exception) As DataTable

    Dim retDataTable As New DataTable

    Try

        Using cn As New iDB2Connection(str)


            Dim sqlText As String = String.Empty
            sqlText = "SELECT username, fullname "
            sqlText += "FROM expusers"

            Try
                ' Open Connection
                cn.Open()
                Using cmd As New iDB2Command(sqlText, cn)
                    Dim dA As New iDB2DataAdapter(sqlText, cn)
                    Try
                        dA.Fill(retDataTable)
                    Catch ex1 As iDB2Exception
                        Throw New Exception("Error in dataAdapter. " + ex1.Message)
                    Catch ex1 As Exception
                        Throw New Exception("Error in dataAdapter. " + ex1.Message)
                    End Try
                End Using
            Catch ex2 As iDB2Exception
                Throw New Exception("Error in connection. " + ex2.Message)
            Catch ex2 As Exception
                Throw New Exception("Error in connection. " + ex2.Message) …
cgeier 187 Junior Poster

You may find more help if you switch to C#. C# seems to be more popular and more examples seem to be available. See my post here on how to use a dataset and tableadapter. It is for C#, but the steps are similar.

cgeier 187 Junior Poster

See the other post on how to use parameters. I am not able to test it on DB2, but I believe that the driver follows the same syntax rules as other database drivers.

cgeier 187 Junior Poster

Use a variable to sum the totals as you add them to listview2. Then after the for loop add a series of '-' (dashes) in each column of a new row. Then add one more row with the total of the totals. I'll leave the implementation to you.

cgeier 187 Junior Poster

Here is another version that uses List--just to show another way to do it.

Version 4 (using List):

We will use our custom class "CarInfo".

CarInfo.vb

Public Class CarInfo
    Public Property name As String
    Public Property total As Integer
End Class

readData:

Private Sub readData()

    Dim cars As New List(Of CarInfo)

    'total # of columns
    Dim totalColumns As Integer = 5

    Dim fileDataArr() As String = File.ReadAllLines(_filename)

    ListView1.Items.Clear()

    For Each line As String In fileDataArr

        'skip any blank lines
        If Not String.IsNullOrEmpty(line) Then
            Dim flds() As String = line.Split(vbTab)

            If flds.Count = totalColumns Then
                Dim entryDate As String = flds(0)
                Dim placano As String = flds(1)
                Dim car As String = flds(2)
                Dim workDone As Integer = flds(3)
                Dim status As String = flds(4)

                ListView1.Items.Add(New ListViewItem({entryDate, placano, car, workDone, status}))

                Dim carExists As Boolean = False
                Dim carIndex As Integer = 0

                'check if car exists in cars array
                If (cars.Count > 0) Then
                    For i As Integer = 0 To cars.Count - 1
                        If cars(i).name = car Then
                            carExists = True
                            carIndex = i
                        End If
                        Next
                End If


                'if car exists in List
                'add value to existing value.
                'Otherwise, add car
                If carExists = True Then
                    cars(carIndex).total += workDone
                Else

                    Dim myCarInfo As New CarInfo
                    myCarInfo.name = car
                    myCarInfo.total = workDone

                    cars.Add(myCarInfo)
                End If
            Else
                MessageBox.Show("Invalid data found in file. Found " & flds.Count & " columns. Expecting " & totalColumns & ". Skipping.", "Invalid Data Found", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End If
        End If
    Next

    'clear …
cgeier 187 Junior Poster

If your teacher asked you to use an array, it is probably better to not use a Dictionary.

Dictionary<TKey, TValue> Class

Represents a collection of keys and values.

It exists in the System.Collections.Generic namespace.

cgeier 187 Junior Poster

Here are 3 different versions.

  • Version 1 uses the dictionary above, mentioned by Reverend Jim.
  • Version 2 uses two arrays.
  • Version 3 uses an array of a class.

Note: Uses a ListView as mentioned by tinsaafl

Controls on form:

  • Button named writeBtn
  • Button named readBtn
  • CheckBox named CheckBox1
  • DateTimePicker named DateTimePicker1
  • NumericUpDown named NumericUpDown1
  • Panel named Panel1
  • RadioButton named RadioButton1
  • RadioButton named RadioButton2
  • RadioButton named RadioButton3
  • ListBox named ListBox1
  • ListView named ListView1
  • ListView named ListView2

Note: Place RadioButtion1, RadioButton2, and RadioButton3 on Panel1.

I have declared the filename a private variable so that it is not hard coded multiple times throughout the program.

Private _filename As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\data.txt"

Form1_Load:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ListBox1.Items.Add("Mercedes")
    ListBox1.Items.Add("Citroen")
    ListBox1.Items.Add("BMW")
    ListBox1.Items.Add("Opel")
    ListBox1.Items.Add("Renault")


    'set View to Details
    ListView1.View = View.Details
    ListView1.Columns.Add("Date", 80, HorizontalAlignment.Left)
    ListView1.Columns.Add("Placano", 60, HorizontalAlignment.Left)
    ListView1.Columns.Add("Car", 60, HorizontalAlignment.Left)
    ListView1.Columns.Add("Work Done", 80, HorizontalAlignment.Left)
    ListView1.Columns.Add("Status", 60, HorizontalAlignment.Left)

    'set View to Details
    ListView2.View = View.Details
    ListView2.Columns.Add("Car", 60, HorizontalAlignment.Left)
    ListView2.Columns.Add("Total", 60, HorizontalAlignment.Left)
End Sub

writeBtn_Click:

Private Sub writeBtn_Click(sender As Object, e As EventArgs) Handles writeBtn.Click
    writeData()
End Sub

readBtn_Click:

Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
    readData()
End Sub

writeData:

Private Sub writeData

        Dim tableArr()

        Dim tableArrfull As Boolean

        If Not tableArrfull Then
            ReDim tableArr(0)
            tableArrfull = True
        Else

            ReDim Preserve tableArr(UBound(tableArr) + 1)

        End If

        Dim date_short As String
        date_short = Format(DateTimePicker1.Value, "dd/MM/yyyy")

        Dim placano As String

        If CheckBox1.Checked = True Then …