VB.NET

Spring 2012

Creating a report in ReportViewer - Annie

1.      Make sure all the field names and table names have no spaces in your database and you have connected your database to VB

2.      Make a new form in VB

3.      Drag the report viewer over from the toolbar to your new form

4.      Once you get the report viewer on you form, you will go to the upper right corner of the report viewer and click the play button.

5.      After you click the play button you will then go to design a new report

6.      Then click the arrow under data source and choice your database

7.      Under the available datasets you will then choice what table you what your data to come from.

8.      After you have done the previous two steps you will then click the next button

9.      The next step is to arrange your fields they way you want them

10.   To just have a list of columns with data just drag everything over under the values box

11.   If you have different fields you want to list, you will put them under the row group box

12.   To total your fields you will pick what field you want to total under the values box. You will then right click on the arrow and choice count. (When you do this it will make all your fields values 1. To make them have a total you have to right click it and select add total. After you have selected add total you then will have to cake the count off the field and just have [fieldname]. ) * Also the Sum function never worked for me, but the count function worked fine.

13.   To add a header to your report you will right click the area above your report in the report design and click add header

14.   After you have added a header you will then right click and choice what you want to put on your header

15.   To make you report to show when you run your program, you will have to go back to your form and click the play button. At the top there is a drop down arrow you will click and then you choice what report you want to show.

Gets the user name of the person who is currently logged on to the Windows operating system - Ashley

 Environment.UserName Property

Fall 2011

 

Thread on the MSDN forums - tells how to open Access reports from Visual Studio - Justin

 http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/201bd86b-0479-4a1e-b20a-fd5621e776f6/

Datagrid code: vb.net - Curtis

First: insert datagrid view on form

Textbox to datagrid:

Imports System.Data.OleDb (Above Public class “FormName”)

Dim “CallName” As New OleDbConnection (Above Private Sub in “FormName” sub)

FormName sub:

“VariableName”.ConnectionString = "provider=microsoft.ace.oledb.12.0;data source= ..\”AccessDatabaseName”.accdb"

“CallName”.Open()

        Dim dt As New DataTable

        Dim ds As New DataSet

        ds.Tables.Add(dt)

        Dim da As New OleDbDataAdapter

 

da = New OleDbDataAdapter("Select * from “Collumfield” where “AccessFieldName” like '%" & “TextBoxName”.Text & "%'", con)

        da.Fill(dt)

        DataGridView1.DataSource = dt.DefaultView

        “CallName”.Close()

Notes:

Database must be copied into Bin folder.

Crystal Report Viewer code VB.net - Curtis

 

First: add crystal report viewer to form

Second: add button, label button View

Imports CrystalDecisions.CrystalReports.Engine

Public Class Exception

    Private Sub ViewButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewButton.Click

        Dim cryRpt As New ReportDocument

        cryRpt.Load("H:\SP2\Visual Basic\Lego Link\Lego Link\”CrystalReportname”.rpt")

        CrystalReportViewer1.ReportSource = cryRpt

        CrystalReportViewer1.Refresh()

    End Sub

End Class

Video showing how to add audio to a form - Ashlei

http://youtu.be/-4oPDeQrtMs

Creating crystal reports - Heather

1. Expand Create New Connection

2. Expand OLE DB(ADO)

3. Select Microsoft offic 12.0 Access Database Engine OLE DB Provider

4. Click next

5. Browse for your database

DO NOT SELECT ANYTHING IN THE OFFICE DATABASE TYPE

Continue through the wizard

To get crystal reports viewer in the toolbox for vb 2010 - Heather

You have to change the framework setting.

1.Click on project on the toolbar.

2. Go down to yourproject properties

3. Click on compile on the side

4. Go to the bottom and click advanced compile options

5. Go to the bottom and change the target framework from .NET framework 4 client profile to .NET framework 4

Save the changes. You may need to restart your program for the changes to take effect. 

To search your database, use this one line of code - Heather

Me.CustomerBindingSource.Filter = "(Phone) = '" & Me.PhoneTextBox.Text & " ' "

-The bindingSource should be the table you are trying to search.

-The (Phone) is the name column to look in.  If it is two words like First Name, you have to use [ ] instead of ()

-The data in the textbox is what the search will look for.

To solve path problems with your database - Heather

Put the database in the debug folder of your project.

example - F:\Senior Project Heather\SportsTech\spforms\bin\Debug\yourDatabase.accdb

Video to get your form to speak to you - Ashlei

http://youtu.be/wxBjWbvbfoc

 

Microsoft's source for Visual Studio 2010 - Justin

http://msdn.microsoft.com/en-us/library/dd831853.aspx

Visual Basic Developer Center - Justin 

Has lots of how-to videos and sample code

http://msdn.microsoft.com/en-us/vbasic/bb466226

To set the Splash Screen in VB .NET - Molly

In the Solution Explorer open the My Project folder. In the Application down select the form you want for your splash screen in the drop down box under "Splash screen:". At the top under "Startup form:" select the form you want to show up after your splash screen. Make sure that at the bottom under "Shutdown mode:" you  select "When startup form closes".

Spring 2011

 

Creating a Crystal Report with Access  Robert

To create a crystal report follow these steps:

Click Project, Add New Item

 When the dialog box appears select Reporting and Crystal Report. Name the report something you can remember associating it with the information you want to report on. Choose Standard Report on the next pop-up. When this box appears Choose Create New Connection. When the drop down menu appears click the + symbol for Access/Excel (DAO) and not the name. In the next box click Database Name.  Find you where you saved your database and click it. (You should have saved your database with an extension of .mdb) Click Finish.  Now select the table you want to add to the Crystal Report. Move it over to the Selected Tables portion and click next. The next few steps are giving you the options on what information you want your report to display, so just go through and set it up for your requirements. To view your report during runtime see my instructions on Viewing Crystal Reports at Runtime below.

Viewing Crystal Reports at runtime - Robert

To display your Crystal Report through VB you need to follow a few steps.

 

1.      Create a windows form. 2.      Drag the Crystal Report Viewer onto the form. 3.      Add a button to the form. (I added two buttons but you can get away with just one.) 4.      Right click the form and select view code. 5.      At the very top add this line of code:

 

Imports CrystalDecisions.CrystalReports.Engine

then click the button you added and add this line of code:

Dim cryRpt As New ReportDocument

cryRpt.Load("C:\Users\williams\Desktop\New Senior Project\WillowSpringCC\WillowSpringCC\ContractsCrystalReport1.rpt")

         CrystalReportViewer1.ReportSource = cryRpt

  CrystalReportViewer1.Refresh()

The cryRpt.Load line of code is where you will determine the path of the Crystal Report. To find the path: Go to the subfolder of your program, look for the report that you want to display (it will have an extension of .rpt at the end)right click on the report and select PROPERTIES. When the dialog box appears go to LOCATION and highlight the path of the report.                                                            

Now paste the path into the line of code that reads:

cryRpt.Load("C:\Users\williams\Desktop\New Senior Project\WillowSpringCC\WillowSpringCC\ContractsCrystalReport1.rpt")

 

The last portion of the path will not be included, you will have to add this particular information manually. To do this go to VB and find the Crystal Report you created and insert the name of the report into the preceding line of code. Now you will be able to view the report during runtime.

                                                                                                          

 

 

Adding forms under one project - Melissa

It is very important to add all your forms under one project, rather than build a new project every time. Create a new project the first time and it will take you to a brand new form, Form1 is the default name. After you have designed the form, you can rename it and save it. You then can right click on your project itsself (the one in bold), not the individual form, and click add new item. It will then take you to the options of things you can add. To add a new form, you click windows form. It will then open another form under your project, default name Form2. You continue to do the same steps until you have designed and created all the forms needed for your project.  If they are not all under the same project, it will not work!! :)

Creating A Report Using a Form - Melissa

To create a report, right click on your project and Add New Item. Choose Reporting on the left, then choose report wizard. Give the report a logical name at the bottom and click on Add. Then it opens a window showing all your dataset choices. Click on the table (view) you want to use and then step through the wizard dragging the fields where you want to display them on the report. That creates the "rdlc" file which is the report itself. Then you create a new form and on that form, drag a Microsoft Report Viewer control to the form. Then in the little popup window you choose the report (rdlc) file you just created. Size it approximately to the size of the report you want viewable

 

How to Maximize your screen and center the content on the form - Jordan

Click on your form and in the properties menu scroll down to Windows
State and select Maximize.

Then to center the content highlight all fields and in the properties menu find Anchor and adjust the anchor as needed.

To allow an update to Access database in Visual Studio - Kenneth

When connecting your data source:

 data>add new data source

database>next

new connection>path to database>test connection

when the pop up that talks about the connection uses a local data file>choose No

(very important or the database will not update)

 

 

Fall 2010

 How to initiate checkboxes or radio buttons - Lisa

 This example is for the radio button, all you need to do for checkboxes is substitue the checkbox name of your event for the radio buttons name below.

Private Sub WonRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WonRadioButton.CheckedChanged

        ' Create and initialize a Radio Button.  

        Dim WonRadioButton As New RadioButton()

        ' Make the radio button control appear as a toggle button.

        WonRadioButton.Appearance = Appearance.Button

        ' Turn off the update of the display on the click of the control.

        WonRadioButton.AutoCheck = False

         ' Add the radio button control to the form.

        Controls.Add(WonRadioButton)

         'InstantiateMyCheckBox

    End Sub

    Private Sub LostRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LostRadioButton.CheckedChanged

         ' Create and initialize a Radio Button.  

        Dim LostRadioButton As New RadioButton()

         ' Make the radio button control appear as a toggle button.

        LostRadioButton.Appearance = Appearance.Button

         ' Turn off the update of the display on the click of the control.

        LostRadioButton.AutoCheck = False

        ' Add the radio button control to the form.

        Controls.Add(LostRadioButton)

         'InstantiateMyCheckBox

    End Sub

End Class

Fixing transparent text boxes - K.C.

 If your text boxes appear normal in design but when you run them they are transparent, here is the quick fix.

Select the form. Then in the properties window, go to the transparency key field and make sure there is no text in the box. If there is, delete it and and then save and run the program. Your text boxes should no longer be transparent.

Setting Database Connection for Crystal Reports - Jake

This code sets the connection of the database for a crystal report when the application is executed and then displays the report in a CrystalReportViewer. This eliminates having to change the path of the database everytime your project is moved to a different location.

 

For this to work your database must be stored in the Debug folder which is in the bin folder of your project. You should also have a CrystalReportViewer placed on the form this code is being used with.

 

    Dim mypath As String = Application.StartupPath

 

‘ Replace rptExample with a descriptive name and

‘ ExampleReport with the name you’ve given the report in your application.

    Dim rptExample As New ExampleReport

Private Sub Form_Load(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles MyBase.Load

 

Try

'Sets the database connection for report.

‘Replace Database.mdb with the name of your database.

rptExample.DataSourceConnections.Item(0). _

SetConnection("", "" & mypath & "\Database.mdb", False)

 

'Sets the report as the ReportSource of the CrystalReportViewer.

Me.CrystalReportViewer1.ReportSource = rptExample

 

Catch ex As CrystalDecisions.ReportSource.EnterpriseLogonException

'Handles any exception.

MsgBox(ex.Message)

End Try

End Sub


Displaying Images Stored in an Access Database - Jake

This code takes an image stored in Access and converts it to a form that can be placed into a PictureBox. To use this code send the reference to the picture stored in Access when the function is called.

 

Private Function GetImageFromByteArray(ByVal picData As Byte()) As Image

‘ Converts the Image(Byte Array) stored in Access into a picture

‘ to view on the form.

 

        If picData Is Nothing Then

            Return Nothing

        End If

 

Dim bmData As Integer = IIf((picData(0) = 21 AndAlso _

picData(1) = 28), 78, 0)

 

        ' Loads the Image.

        Dim img As Image = Nothing

        Try

            Dim ms As New MemoryStream(picData, bmData, _

picData.Length - bmData)

            img = Image.FromStream(ms)

        Catch

        End Try

 

        ' Returns the Image.

        Return img

End Function

 

Working with a MonthCalendar Control - Jake

This code diplays data queried from an Access database that contains a selected date from a MonthCalendar. The queried data is displayed in a DataGridView and is changed every time a different date selected in the MonthCalendar control.

For this to work your database must be stored in the Debug folder which is in the bin folder of your project. You should also have a MonthCalendar and DataGridView placed on the form this code is being used with.

 

Dim mypath = Application.StartupPath & "\Database.mdb"

Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath)

Private Sub MonthCalendar1_DateChanged(ByVal sender As System.Object, _

ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles _ MonthCalendar1.DateChanged

 

‘ Calls DisplayAppointments() to change data displayed everytime a

‘ different date is clicked in the MonthCalendar.

        Call DisplayAppointments()

End Sub

Private Sub Form_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

‘ Calls DisplayAppointments() to display data when form is first loaded.

 

        Call DisplayAppointments()

End Sub

Private Function DisplayAppointments()

        'Displays the appointments for the date selected in the MonthCalendar.

 

        Dim SelectedDate As Date = _

MonthCalendar1.SelectionStart.ToShortDateString()

 

‘ Change the SQL Query in quotes to the fields and table in your

‘ database.

  Dim Sql As String = "SELECT * FROM TableName WHERE Date = #" & _                                                           SelectedDate & "#"

 

        Dim cmd As New OleDb.OleDbCommand

 

        conn.Open()

 

        cmd.CommandType = Data.CommandType.Text

        cmd.CommandText = Sql

        cmd.Connection = conn

 

        Dim da As New OleDb.OleDbDataAdapter(cmd)

 

        Dim ds As New DataSet

 

        Try

 

‘ Change NewTable to a descriptive name for the new table

‘ containing the data the SQL Query returns.

            da.Fill(ds, "NewTable")

            DataGridView1.DataSource = ds.Tables("NewTable")

            DataGridView1.AutoSizeColumnsMode = _

                                    DataGridViewAutoSizeColumnsMode.Fill

 

        Catch ex As Exception

            'Handles any exception.

            MessageBox.Show(ex.Message)

  End Try

 

        conn.Close()

        Return Nothing

End Function

 

Fall 2009

Setting the Tab Order - Jason

While creating the GUI’s in a visual basic interface, you may sporadically place textboxes, labels, combo boxes, and other controls onto your form(s).  When this is done, the tab order will be random as well.  There is a simple way of getting your tab order correct to allow more efficient data entry.

1.     Select the form (not the controls)

2.     Click the ‘View’ tab from the toolbar

3.     Click the ‘Tab Order’ option from the menu that drops down

The mouse pointer will become a crosshair (only when it’s over a control) and all of the controls on the form will blue boxes with numbers in them.

4.     Next, just click the blue box of the control in the order in which the tab button should navigate them.

5.     After all of the desired controls are set, just return to the ‘View’ tab and deselect the ‘Tab Order’ option

Progress Bar - Samantha

If you want your progress bar to work on you Visual Basic program you have to be sure to add a blank label with nothing typed inside of it. If you put some words into the lab it will cause the entire page of code not to work.

 

How to add different colors a reports records - Samantha

1.       Go to the Main Report View of your Crystal Report

2.       Right click on one of the Sections( Section 1, Section 2, etc)

3.       Select Section Expert

4.       Go to the format section of the Details

5.       Click the color Tab

6.       Click the Check Box next to the Background Color

7.       Pick which color you want. ( I will use Silver as an example)

8.       Click the X-2 button next to the color drop down box

9.       Enter this code into the Formula Editor:

If RecordNumber Mod 2 = 0 then crSilver else crNoColor

10.   Save and Close the editor.

Spring 2009

 

Quick and easy way to make a custom splash screen - Nicholas

Make a form and call it splash. Design it up and make it look pretty.

Add a timer to the page and inside the timer place this code.

 

Timer1.Enabled = False

XXXXXXXX.Show() --The form you want to show after splash--

Me.Hide()

 

In the timer proprieties set the behavior enabled to true and the interval to the time you want the splash screen to display. Every 1000 = 1 second so 7000 = 7 seconds once done set the splash as the first form to display and set splashscreen to (None).

 

To set your display fields to ReadOnly - Nicholas

Click the TextBox1 and set property ReadOnly to True. Then under the "+" Click Event of the binding navigator and this code:

TextBox1.ReadOnly = False

Then under the Click Event of the Save button and this code:

TextBox1.ReadOnly = True

Now when you want to add a record the field will become available to alter and when you click save the fields will return to ReadOnly so they cant be altered.

 

To write to a populated combo box - Chris

   Private Sub newButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newButton.Click

        'Begin the add operation

        Try

            With Me.yourBindingSource

                .EndEdit()

                .AddNew()

            End With

            With Me

                .addingBoolean = True

                .setComboboxBinding()

                .whateverComboBox.Focus()

              If .whateverComboBox.SelectedIndex <> -1 Then

                'save the index of the new record for later navigation

                .previousSelectedIndex = .Member_NameComboBox.Items.Count - 1

                Else

                    .previousSelectedIndex = 0

              End If

 

            End With

        Catch ex As Exception

            MessageBox.Show("Error on Add New: " & ex.Message)

        End Try

    End Sub

 

Add this subroutine to change the combo box property - Chris

Private Sub setComboboxBinding()

        'set the combo box to save any changes

        'saves for add or edit, not during navigation.

 

        With Me.whateverComboBox

            If (addingBoolean Or editingBoolean) Then

                .DataBindings!text.DataSourceUpdateMode = _

                DataSourceUpdateMode.OnValidation

                .DropDownStyle = ComboBoxStyle.Simple

            Else

                .DataBindings!text.DataSourceUpdateMode = _

                DataSourceUpdateMode.Never

                .DropDownStyle = ComboBoxStyle.DropDownList

            End If

        End With

    End Sub

  

Place this code in a save button to change the combo box back to read only - Chris

With Me

            Try

                .MembersBindingSource.EndEdit()

                .addingBoolean = False

                .editingBoolean = False

                .setComboboxBinding()

                .Member_NameComboBox.SelectedIndex = .previousSelectedIndex

 

            Catch ex As Exception

                ' catch duplicate records and constraint violations

                MessageBox.Show(ex.Message)

            End Try

        End With

**Adding Boolean and Editing Boolean are globally declared as = False

Private addingBoolean As Boolean = False

 

Set up your reports for a real time query using a combo box - Chris

http://vb.net-informations.com/crystal-report/vb.net_crystal_report_parameter_string.htm

 

 

Anchor Property of Screen - Chris

In order to make sure the controls on your forms are centered when the page is maximized, highlight all the controls on your form and set the anchor property to none.

 

A  Mdi Project will make one form the frame in which every other form opens will be inside - Chris

On the form you want to use as the container, set the isMdiContainer property to true.

 

Place this code in each menu strip item that will open a new (child) form - Chris

Private Sub ContractsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ContractsToolStripMenuItem.Click

        Dim acontactform As Contracts = Contracts.instance

        With acontactform

            .MdiParent = Me

            .Show()

            .Focus()

        End With

    End Sub

Closing a form then trying to reopen it can throw a dispose error.  Place this code on each child form. - Chris

  Private Sub contracts_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        e.Cancel = True

        Me.Hide()

    End Sub

This will cause the program to not dispose of the page, making it accessible still.  Make sure any exit buttons use me.hide() instead of me.close()

 

Substring (as copied from http://www.homeandlearn.co.uk/net/vbNet.html ) - Kenny

This allows you to grab one string within another. (For example, if you wanted to grab the ".com" from the email address "me@me.com")

In between the round brackets of Substring( ), you specify a starting position, and then how many characters you want to grab (the count starts at zero again). Like this:

Dim Email as String
Dim DotCom as String

Email = "me@me.com"
DotCom = Email.
Substring(5, 4)

MsgBox(DotCom)

The message box would then display the characters grabbed from the string, in this case the ".com" at the end (start at position 5 in the string and grab 4 characters).

How to make it so you don’t have to change a Path from computer to computer - Michael

Most of the time, when you move from one computer to another you have to change the path of where your jump drive is in your program. There is a couple lines of code that you can use to make that problem go away.  In my program I have everything in one folder and it is good to do this. Here is the path of my program F:\Senior Project\The Mulligan\ then my Website is under F:\Senior Project\.

      string Es = Path.GetDirectoryName(Application.ExecutablePath);

     string[] Column = Es.Split('\\');

     string Root = Column[0];

     string Sub = Column[1];

     string path = Root + @"\" + Sub + @"\" + @"\Website.htm";

 F: would be in the string Root and Senior Project would be in Sub.

You then just string it all together in the string Path. This code is only for if it is in one sub folder you would have to add more to it to make it if it is in another.

Create a Relationship Diagram with VB.net - Michael

After you have started your program and have the database linked to your program you can view an entity relation diagram, or ERD, inside of VB.net.  To do this you have to have your data sources pane up. If it is not you can click Data on the toolbar then go to Show Data Sourcers. After it is up you Click the Edit DataSet with Designer, it is the icon that is highlighted in blue in the picture below.

 It will show you your ERD in the middle of your screen from there you can just hit print in the toolbar.

Fall 2008

General Hint - Antonio

A good idea when you start building your forms for your project is to save a copy of the project with just the forms and base coding you have.  Always keep a backup of this base file, so you don’t have to start over from scratch if something goes wrong when you start to connecting your forms your access database.  If you have this base file the only thing you should have to do is reconnect your project to the database and start over from there.

Crystal Report Hints - Antonio

(Once you have gotten your CRUD programming to work on your project.)  When connecting your crystal reports to the database make sure your crystal reports are connected to the copy of the database that is in the debug folder of your project.  This will ensure that when you add or delete a record from your project that it will show the changes on your crystal reports automatically.

Error Hints- Antonio

Unable to copy file "obj\Debug\vgamestore.exe" to "bin\Debug\vgamestore.exe". The process cannot access the file 'bin\Debug\vgamestore.exe' because it is being used by another process.

When you get a similar error like the one above when you try to debug your program, the following might help fix this error:  Stop running your storage device (cd or memory stick) by taking it out of the computer that you are running your project from.  Insert your device back into the computer and try debugging your project again and that error should go away.

  

Using Access and VB.Net - Erica

If you are planing to use access 2007 make sure to convert it to access 2002-2003 version. To do this you go to save as then choose file type 02-03 format.

 

Crystal Report Not Working On Different Computers - Erica

If your Crystal Reports don't work on different computers you need to go and change the path to your file. By doing this you would you will open up the Crystal Report in your program then go to the main form and a screen will pop up. This screen is so you can change the path of your report.

 

Having Trouble Seeing Website - Erica

If you are having trouble seeing your web-page on different computers. Don't worry just redirect the path of it and it should work. For example if code is procees.start("F:\seniorproject/website.htm") the F drive may have to be changed to whatever the computer has the drive named as.

 

TAB ORDERING - Kyle Tucker

 

1. Open up the form.

2. Click on "View" main menu

3. Click on "Tab Order"

4. Click the text box you want your cursor to start in, and then click the next text box where you want the cursor to go to next...repeat until you have clicked on all the text boxes you want to tab over to.

 5. when finished...go back the view tab and click on tab order again.

 

Having problems connecting your Access database to your project in VB? - Felicia

 

If you used Access 2007 to create your database,you may have a problem connecting.

What you need to do is convert your database to an earlier version like 2003. Open up your database, click file-Save As, and choose the 2003 version. Place a copy into your Bin/Debug folder, and then reconnect. It should move you on to the next step.

 

Logging in with the Enter key - Brandon

Instead of having to click the login button you can login with the Enter key.  To do this you must declare the function getasynckeystate as a global variable.

Public Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal vKey As Int32) As UShort

Create a function named password check.

Private Function passwordcheck()

        'Checks to see if the password is correct.

        If txtuser.Text = "Brandon" And txtpassword.Text = "password" Then

            Me.Close()

            frmMainPage.Show()

        Else

            MessageBox.Show("Invalid User Name and/or Password", "Login Error", _

            MessageBoxButtons.OK)

        End If

       End Function

Set the login button code to call the password check function.

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click

'Login button verifies username and password by calling the passwordcheck function.

        Call passwordcheck()

         End Sub

Set the password textbox as a keydown event

 

Private Sub txtpassword_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtpassword.KeyDown

        'Enables the user to login by way of pressing the enter key

        'once the username and password have been entered.

 

        If GetAsyncKeyState(13) Then

            Call passwordcheck()

        End If

    End Sub

Now you should be able to type the username and password to your system and then press enter to login instead of having to click the login button.

 

A simple way to get your webpage to display while running your program - Brandon

key system.diagnostics.process.start(location of file) behind your webpage button code.  The book of knowledge on this site has a different method listed as well.

Private Sub btnWebPage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWebPage.Click

        'Button displays the webpage.

 

        Try

            System.Diagnostics.Process.Start("F:\senior project\website.htm")

        Catch

            MessageBox.Show("Error loading the Website.  Website not found.", "Error", MessageBoxButtons.OK)

        End Try

 

    End Sub

 

 

 

Have textboxes display the current date and time via a button - Brandon 

This was useful because it speeds up the entry of sales into the system.

Private Sub btnDate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDate.Click

        'Button updates txttime and txtdate with current time/date.

 

        If txttime.Text = "" And txtdate.Text = "" Then

            txttime.Text = TimeString

            txtdate.Text = Today

        Else : MessageBox.Show("A new record must be created before the date/time can be inserted", "Error", MessageBoxButtons.OK)

        End If

    End Sub

 

 

Invalid path solution – Changing the path of your Database Connection – Kyle

Does your system work on one computer and not on another? Does your program have trouble finding your database? You might want to change the connection path

Example: On one computer, my system ran fine without any problems.  The jump drive was set as the “F:” Drive. When I tried running my system on a different computer, my drive would be set as the “E:” drive and I would get some sort of exception like “Invalid Path”.  It seemed like my program couldn’t connect to my database.

I was told the only way to solve it was to reconnect my program to the database. However, I found an easier and much faster way of solving the problem without going through the hassle of reconnecting everything.

1)      Look in the Solution Explorer and double click on “My Project”

2)      On the left hand side you will see list of tabs. Click on the “Settings” tab.

3)      Under the “Value” heading, click on the first connection and then the three dots and the end.

4)      Click in the “Database File Name” box and press the “Home” key.

5)      Change the name of the drive to whatever your jump drive is on the computer.

a.       Example( Change the E: to F: )

6)      Click on “Test connection”

7)      You are finished! Go run your system again and see if it works properly.

 How to set up the connection to your database to make it update properly. – Kyle

After the connection has been established

You will be prompted to save a copy to your project.

Select NO!

Select the tables needed and click finish.

In the Binding Navigator create a new button for your update

Here is the code to that goes behind that button…

        Me.Validate()

        Me.BindingSource1.EndEdit()

        Me.Customer_TableTableAdapter.Update(Me.TWFS_Database_copyDataSet3)

      Make sure you enter your table adapter name and Data Set.

 For a smooth transition between forms - Felicia

Add a main menu button to each form. This makes it look more professional than having to exit out of each form.

Here is the code:

frmMenu.Show()

Me.Hide()

 

Tip: Add a report button to all of your report forms as well. Just use the same code to get back to the report menu.

 

How to get records from crystal reports to change - Vaneisha

Do not worry about this. There is no code required for this activity. If you code everything else properly, this should definitely work on its own. However, you should make sure that the database that you are trying to update is in the “bin” folder.

 

How to connect a navigating bar to a database - Vaneisha

* You cannot connect a bindingNavigator without first connecting the bindingSource to the form

1. Add the bindingNavigator to the form

2. Select it and go to Properties

3. Find binding source on the properties list

4. Chose the desired binding source  

 

 Use this code in your click event to start a process such as a batch job or opening a web page - Darren

 System.Diagnostics.Process.Start("C:\start.bat”)

Starts a batch file on your C:\ drive.

  

System.Diagnostics.Process.Start("www.hotmail.com")

Opens Hotmail in your default web browser.

 

Using Microsoft Publisher to create a web page - Walter

 

When adding Microsoft Publisher to website: Go to file save as, then Save the publisher file as webpage,filtered(*.htm).

 Then add this code behind the label or button which shows the path of the website

 

Private Sub llinkSite_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llinkSite.LinkClicked

'loads the website

Process.Start("E:WALT\InputOutput\Website.htm")

 

End Sub

 

 Open and display a picture using the file dialog box with a filter. - DeAnna

 Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenButton.Click

        'Resets the dialog box to be blank

        OpenFileDialog1.Reset()

        'Opens the file dialog box

        With OpenFileDialog1

            .CheckFileExists = True

            .ShowReadOnly = False

             'Filters what file type will show in the file dialog box

            .Filter = "Bitmap Files(*.BMP)|*.BMP"

             If .ShowDialog = Windows.Forms.DialogResult.OK Then

                'Inserts the image to the picture box

                PictureBox1.Image = Image.FromFile(.FileName)

            End If

        End With

End Sub

  

'Want to use the Binding Navigator to delete a record but be prompted? - DeAnna '

After you have bound it with the database.'Click the binding navigator and go to its properties.

'Set "Delete Item" property to none.'Double click the delete button on the form.'Apply this code:

Private Sub BindingNavigatorDeleteItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorDeleteItem.Click

        'The user clicked the delete button.

        If MessageBox.Show("Are you sure you want to delete the current record?", _

        "Confirm Delete", _

        MessageBoxButtons.YesNo, _

        MessageBoxIcon.Question, _

        MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then

            'Delete the record.

            Me.BindingNavigator1.BindingSource.RemoveCurrent()

        End If

End Sub

 

Spring 2008

Problems with seeing your updated forms? - Cherie & Calvin

Once you update a field and save it, first view the information in the access table in your bin folder,  after seeing the update information, go back to the VB program open your project and delete your connections to the access tables. It should be two icons with gold bars in the solutions explorer window. It’s safe to delete them both and reconnect. After this, reestablish your connection and run your program, view the field you updated and it should be there.

 WARNING…………Be sure you know how to connect to your access table and only update your access table in your BIN folder.

 Create shortcuts for buttons - Calvin

 Place “&” before the text you place in the regular text box, after this a small underline will appear under the first letter of the word. Use the control button and the press the letter that’s underlined for that button to execute that button with the short cut.

 Avoiding Crystal Report crashes - Calvin

 If you need to delete a crystal report, be sure to undock the report from the screen. To do this go to the little arrow to the right of the crystal report its self, click the button and at the bottom of the submenu and select the “undock from parent screen” option, after this you can delete the crystal report will out deleting the form it self. If you delete the report while its still “dock to the parent screen” it will disable the form completely

Fall 2007

 

Enter the date and time into a status bar - Micah

To view the date

1. drag and drop the status strip from your toolbox

2. in the drop down box select status label

3. change the status labels (Name) to dateToolStripStatusLabel

4. delete the text so it appears empty on the form

 

To view the time

1. press the drop down box again and select another ToolStripStatusLabel

2. change the status label (Name) to TimeToolStripStatusLabel

3. delete the text so it appears empty on the form

 

The code:

double click the form so the form_load code will appear and code these lines of code so your date and time will appear on the form

 

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

 

Me.dateToolStripStatusLabel.Text = Today.ToShortDateString

Me.TimeToolStripStatusLabel2.Text = Now.ToShortTimeString

 

End Sub

 

 

Where to save your database - Miranda

For C# and Visual Basic, save the access database within the debug folder. This is found within your project folder, by clicking on the folder with the name of your project, and then select the folder that says bin, and finally the folder that says debug.

 

Naming your database and project - Phill

 If you don't want to start your project over, save your files with a straight forward names. When connecting your database to your VB, blanks and special characters may be changed to underscores which then will not match your actual file names.  This causes data items not to be recognized.

1. No apostrophes or special characters

2. No blanks or spaces

 

Where to store your database - Aaron 

If you are using VB.Net and ACCESS be very careful when linking the database to your project. Make sure you store a copy of your database in the "bin" folder of your VB.Net project and use that source to link the database to the project.

 

Code to add a save/update button - Aaron

 First, add a button to the Binding Navigator and double-click it to edit the code behind the button. 

Add the following code:

 

Me.Validate()

Me.tablenameBindingSource.EndEdit()

Me.tablenameTableAdapter.Update(Me.datasetname.tablename)

 

*All instances where there is an underlined portion, you should enter YOUR database and dataset names !!! (very important !!)  Save and Test !!

 

Spring 2007

 

How to convert separate forms into one form using Visual Basic 2005 - Josh

Step 1: Open the main form your users will see.

Step 2: From the File menu, click Add Existing Project. From here, select the additional forms you wish to add. Do this step as many times necessary.

Step 3: Ensuring each form has a different, unique name, drag the form, as well as any databases or supplemental materials, over the first form’s name in bold print. Do this step as many times necessary.

Step 4: Delete all “old” forms that have already been dragged to main form. This step may be optional.

 

Code to perform an interface with multiple forms using Visual Basic 2005 - Josh

Dim CurrentPageName As New NewPageName

NewPageName.Show()

Me.Hide()

Spring 2006

 

How to insert a calculator into VB.Net - Marquita

    Dim total1 As Integer

    Dim total2 As Integer

    Private Sub btnZero_Click(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) _

    Handles btnZero.Click

 

        txtDisplay.Text = txtDisplay.Text & btnZero.Text

    End Sub

    Private Sub btn2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTwo.Click

 

        txtDisplay.Text = txtDisplay.Text & btnTwo.Text

    End Sub

    Private Sub btnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOne.Click

 

        txtDisplay.Text = txtDisplay.Text & btnOne.Text

    End Sub

    Private Sub btnThree_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThree.Click

 

        txtDisplay.Text = txtDisplay.Text & btnThree.Text

    End Sub

    Private Sub btnFour_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFour.Click

 

        txtDisplay.Text = txtDisplay.Text & btnFour.Text

    End Sub

    Private Sub btnFive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFive.Click

 

        txtDisplay.Text = txtDisplay.Text & btnFive.Text

    End Sub

    Private Sub btnSix_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSix.Click

 

        txtDisplay.Text = txtDisplay.Text & btnSix.Text

    End Sub

    Private Sub btnSeven_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSeven.Click

 

        txtDisplay.Text = txtDisplay.Text & btnSeven.Text

    End Sub

    Private Sub btnEight_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEight.Click

 

        txtDisplay.Text = txtDisplay.Text & btnEight.Text

 

    End Sub

    Private Sub btnNine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNine.Click

 

        txtDisplay.Text = txtDisplay.Text & btnNine.Text

    End Sub

 

    Private Sub btnPlus_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnPlus.Click

        total1 = total1 + Val(txtDisplay.Text)

        txtDisplay.Clear()

    End Sub

 

    Private Sub btnEqual_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEqual.Click

        total2 = total1 + Val(txtDisplay.Text)

        txtDisplay.Text = total2

    End Sub

End Class

 

Display the current date in a label on your form: - Tillie

  1. Add a label to your form from the toolbox
  2. Remove the text for the text box.
  3. Click on the timer and in the properties window, set “Enabled” to True.
  4. Double-click on the timer and insert the following line of code:
    • Label2.Text = Today

 

Set the maximum number of characters in a textbox (VB.Net) – Tillie

Click on the textbox (ex. Phone number).  Then in the Properties window, find “maxLength” and set it to the number of choice. (Example: Phone number’s maxLength could have 10 digits, so set the maxLength to 10.)  With this feature, you can make sure that you are not inserting too much data.

 

Make password appear as an *: - Tillie

Click on the password textbox.  Then, in the properties window, find "passwordChar".  In the box beside it, type in an asterisk.  " * ".

 

Lock a textbox: - Tillie

For an ID number, the user of the program shouldn't be able to change the unique ID number, so you should lock that text box.  Just click on the textbox, and in the properties window, find "Locked".  Change this to True.

 

Using this code will change your button into a polygon shape-Marquita.

Private Sub Main_Menu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' Define the points in the polygonal path.

        Dim pts() As Point = { _

            New Point(5, 15), _

            New Point(35, 15), _

            New Point(35, 5), _

            New Point(55, 25), _

            New Point(35, 45), _

            New Point(35, 35), _

            New Point(5, 35) _

        }

 

        ' Make the GraphicsPath.

        Dim polygon_path As New GraphicsPath(FillMode.Winding)

        polygon_path.AddPolygon(pts)

 

        ' Convert the GraphicsPath into a Region.

        Dim polygon_region = New Region(polygon_path)

 

        ' Constrain the button to the region.

        Button1.Region = polygon_region

 

        ' Make the button fit the region.

        Button1.SetBounds(Button1.Location.X, _

            Button1.Location.Y, pts(3).X + 5, pts(4).Y + 5)

    End Sub

 

Using this code will allow you to rotate text around your graphic-Marquita

 

Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click

        Static angle As Long    ' Angle in degrees.

 

        ' Make a GraphicsPath that draws the text

        ' at (150, 150).

        Dim graphics_path As New GraphicsPath(Drawing.Drawing2D.FillMode.Winding)

        graphics_path.AddString("Alexius and Shaniyah Antique Doll System", _

            New FontFamily("Times New Roman"), _

            FontStyle.Bold, 20, _

            New Point(120, 120), _

            StringFormat.GenericDefault)

 

        ' Make a rotation matrix representing

        ' rotation around the point (150, 150).

        Dim rotation_matrix As New Matrix

        angle += 20

        rotation_matrix.RotateAt(angle, New PointF(120, 120))

 

        ' Transform the GraphicsPath.

        graphics_path.Transform(rotation_matrix)

 

        ' Draw the text.

        With Me.CreateGraphics

            .Clear(Me.BackColor)

            .FillPath(Brushes.Blue, graphics_path)

        End With

    End Sub


 

 

Connecting to your (Access) database without going through the Connection steps - Timmy

Use the following code:

 

  • This line of goes in the on the Connection String Property.
  • Click on your form’s connection and go to the Connection String Property.
  • Notice the “Provider =” at the beginning of the code.
  • Where the “=” is located in the code you put your connection type and if you have a password enter it between the “ “
  • The Admin User ID is set at default as Admin
  • Sourse = ../../your database.mdb

 

Provider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;Data Source=../../SAR.mdb;

 

This will allow you to connect to your database without going through the steps of connection through the Server Explorer.

 

Code a progress bar to simulate loading application - Timmy

 

  • Add the progress bar to your form
  • Add a label under your progress bar
  • Add a timer to your form
  • On Form load enable your timer
  • Set you parameters on your time_click
  • Use the following code

If ProgressBar1.Value <> ProgressBar1.Maximum Then

                      ProgressBar1.Value = (ProgressBar1.Value + 1)

Label5.Text = "Loading " & ProgressBar1.Value & "% Complete"

      End If

  • Then set your intervals to allow the timer to move

                        If ProgressBar1.Value = 1 Then

                        Timer1.Interval = 800

        End If

  • On the Interval, the higher the interval the longer it takes to load. Use several of the above line of code to allow the progress bar to move.
  • Then the following code will allow you to display the code and open different forms.

If ProgressBar1.Value = 100 Then

                    Label2.Text = "Loading Complete"

                    Dim FrmLogin As New LoginForm

                    FrmLogin.Show()

            ' Hide the login form

                    Me.Hide()

                    Dim SplashForm As New SplashForm

                    Me.Hide()

                    Me.Visible = False

                    Timer1.Enabled = False

End If

Now you have a progress bar!!

 

Creating an xml news ticker in VB.Net - Matt

First create an xml file with the following code:

 

<?xml version="1.0" encoding="utf-8" ?>

- <ticker>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

  <news>Joe's Tire and Lube</news>

</ticker>

 

The following will need to be declared in the form

Dim Thread1 As New System.Threading.Thread(AddressOf Counter1.Count)

    Dim widthX As Single

    Dim heightY As Single = 0

    Dim g As Graphics

    Dim xmlst As String      'string from the xml file

    Dim fo As Font

    Dim str As String

    Dim strwidth As SizeF    'gets the xml string's width and height

    Dim douX As Double       'stores the xmlstring's width    

 

Next in the form load put in the following code:

' get news ticker

        '''''News ticker

        g = Me.CreateGraphics()  'get the graphics object of the form

        widthX = Me.Width        ' x co- ordinate or width

        Debug.Write(String.Format("The width is {0}", CStr(Me.Width)))

        Me.loadthenews()

        Dim gr As Graphics

        Timer1.Interval = 100

        Timer1.Start()

        fo = New Font("Times New Roman", 20, FontStyle.Bold, GraphicsUnit.Point)

        strwidth = g.MeasureString(str, fo)

        douX = strwidth.Width

 

Next create a timer component and code the following:

'Set properties for news ticker

        g.Clear(Me.BackColor)

        g.DrawString(str, fo, Brushes.Black, widthX, heightY)

                If widthX <= (0 - douX) Then  'check whether all   text ‘have been  scrolled

            widthX = Me.Width

        Else

            widthX -= 5

        End If

 

Other code that will need to be in the form:

   Private Sub NewsTicker_hover(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MouseHover

        Timer1.Stop()

        Debug.Write(String.Format("The string width is {0}", CStr(douX)))

    End Sub

    Private Sub NewsTicker_leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MouseLeave

        Timer1.Start()

    End Sub

 

Code for an easy search in VB.Net and Access - Matt

Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)

' declare oledb command

Dim cmd As OleDb.OleDbCommand

' declare counter for failed password attempts

 

Dim sql = "SELECT * FROM Customer WHERE VinNumber='" & txtVinNumber.Text & "' OR LastName='" & txtLastName.Text & "'"

 

cmd = New OleDb.OleDbCommand(sql, conn)

conn.Open()

Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader

 

        Try

            If dr.Read = False Then

                If MessageBox.Show("Record Not Found. Do you want add a record?", "Customer1", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then

                    Try

                        StoredVinNumber = txtVinNumber.Text

                        btnAdd_Click(sender, e)

                        txtVinNumber.Text = StoredVinNumber

                    Catch

                        MessageBox.Show("Error saving the file", "Customer1")

                    End Try

                End If

            Else

                MessageBox.Show("Record Found...")

                '  txtRecordNumber.Text = dr.FieldCount.ToString - 1 & " Records Searched "

                txtVinNumber.Text = dr("VinNumber").ToString

                txtFirstName.Text = dr("FirstName").ToString

                txtLastName.Text = dr("LastName").ToString

                txtAddress.Text = dr("Address").ToString

                txtCity.Text = dr("City").ToString

                txtState.Text = dr("State").ToString

                txtZip.Text = dr("Zip").ToString

                LockTextBoxes()

            End If

        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

        conn.Close()

 

String reader in VB.Net - The following code allows for comparing parts of string values - Matt

'Show the vehicle specs for the Vin Number

        Dim VinReader As String = txtVinNumber.Text

‘This will allow code to look at positions 0 – 10.       

VinReader = VinReader.Substring(0, 10)

‘Here you would setup your if statements

 

Various Items - Neka

-MaxLength: For text input, you can put a limit on the number of characters the user can type into the text box with this property. For instance, if you created a text box where the user had to enter in his password and the password would always be 10 characters or less, you could set the .MaxLength property of the text box to 10. When the user tries to type the 11th character, he will receive a beep.

- .Multiline: If the .Multiline property is set to true, then when the user presses enter the cursor will go to the next line, like a word processor. Be sure you make the text box high enough for the user to type several lines if you don't plan to make a Vertical scroll bar.

- .Password Char: If you've ever seen a password input box, you'll notice that the password the user type isn’t printed in regular characters for the whole world to see; rather, asterisks are displayed for each character the user types. If you are doing a password input box, the .Password Char property can be useful since it sets what character appears when the user types. You would usually want to set this to *, but anything else can be used as well.

- .Scrollbars: There are 4 possible values which can be set for this control:

 

0 - None

1 - Horizontal

2 - Vertical

4 - Both

 

If you have the .Multiline property set to true, you will usually want the Scrollbars property set to 2 (vertical). When one of these is set, scroll bars appear on the text box so the user can control where the visual window is. If a Horizontal scroll bar is enabled with the text box, then the user will have to push enter to advance to the next line since it will continue scrolling to the right without change.

 

Here is Code that makes your form fade in and out just to add some spice to it - Kris

Dim Clear as Double

'Fade In

'Always use 1.01 instead of 1 or your form will have a tiny bit 'of transparency left which can sometimes really slow things 'down.

For Clear = 0 to 1.01 step 0.01

    Me.Opacity = Clear

Next

'Fade Out

For Clear = 1 to 0 step -0.01

    Me. Opacity = Clear

Next

To maximize the crystal report forms & other forms in VB.net - Candis

1.) Go to the properties on the form

2.) Go down to WindowsState

3). Click the drop down and set to Maximum

 

Also to center your forms in VB.net

1) Go to the properties on the form

2) Go down to the StartPosition

3) Click the drop down and set the CenterScreen

 

This website allows you to convert code from programs in C# to Vb.Net or from Vb.Net to C# - Candis

 

http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx

 

Create a splash screen with a progress bar - Jessica

 

Add a progress bar control, a label, and a timer control to the form.

Behind the form load event, the code is as follows:

 

Private Sub Splash_Screen_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        '   This enables the timer to start counting.

        Timer1.Enabled = True

End Sub

 

Then, there will be a separate event for as the timer ticks:

 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

      

        If ProgressBar1.Value <> ProgressBar1.Maximum Then

            ProgressBar1.Value = (ProgressBar1.Value + 1)

            lblLoad.Text = "Loading " & ProgressBar1.Value & "% Complete"

        End If

 

        '   The following five If Statements change the interval for the

        '   timer to load the system.

        If ProgressBar1.Value = 1 Then

            Timer1.Interval = 800

        End If

 

        If ProgressBar1.Value = 2 Then

            Timer1.Interval = 75

        End If

 

        If ProgressBar1.Value = 12 Then

            Timer1.Interval = 600

        End If

 

        If ProgressBar1.Value = 14 Then

            Timer1.Interval = 4000

        End If

 

        If ProgressBar1.Value = 15 Then

            Timer1.Interval = 1

        End If

 

        '   This loads the login screen when the progress reaches 99.

        Dim Login_Screen As New Login_Screen

        If ProgressBar1.Value = 99 Then

            Login_Screen.Visible = True

            Me.Visible = False

        End If

    End Sub

The numbers can be played around with to adjust how fast or slow the progress bar moves. The lower the number, the faster it will go.

 

To get a date in a text box to keep from displaying '12:00:00 AM' after the date - Jessica

Use the following line of code (replacing txtBirthDate.Text with the name of the specific text box on the form):

 

txtBirthDate.Text = Format(DateTime.Parse(txtBirthDate.Text))

 

It will go in your form load event, and behind the first, next, previous, and last buttons.

 

 

This will format the date  -  Candis

 

This will format date in long & time in Short or Long. To do this just change the ShortDate on the end to LongDate or ShortTime or LongTime

 

Place this in the form load

Change txtDate.Text to your textbox or label that display the date

 

txtDate.Text = FormatDateTime(CDate(txtDate.Text), DateFormat.ShortDate)

  

To create a timer controlled splash screen for any project - Jim

Start by adding a new class to your project and name it Count1.

In the new Count1.vb class enter the following (minus the first and last line of course):

    Public Class Count1

        Public CountTo As Integer

        Public Event FinishedCounting(ByVal NumberOfMatches As Integer)

         Sub Count()

            Dim ind, tot As Integer

            tot = 0

            For ind = 1 To CountTo

                tot += 1

            Next ind

            RaiseEvent FinishedCounting(tot)

             'makes the FinishedCounting event to occur

        End Sub

    End Class

Once that’s done, add a new form to your project and call it frmSplash.vb

Put a label on the form with a big "welcome" in it. :)

Next, open your projects startup form, and add the following two variables.

   Dim counter1 As New Count1

   Dim Thread1 As New System.Threading.Thread(AddressOf counter1.Count)

Last, double click on the form to open the form_load event and add the following:

    Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Hide()

        Dim frmSplash As New frmSplash

        frmSplash.Show()

        frmSplash.Update()

        Thread1.Sleep(5000)

        frmSplash.Close()

        Me.Visible = True

    End Sub

That's it. Run your program and the frmSplash will run for how ever long you tell it. In this case 5000 nanoseconds or 5 seconds.

 

This will display the Time & Date on the form in VB.Net – Candis

From the toolbar, click Windows Forms, and drag the timer to the form

First place the StatusBar on the form

Second drag the Timer on the form ,  Double click on the timer and type

 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

StatusBar1.Text = TimeOfDay.Now

End Sub

Third Go to the properties of the Timer  Set Enable to TRUE  & Interval to 1000

Coding for a multi-user password system using VB.Net and Access - Matt

 

Create a table with two columns, one for the user name and the other for the password.  Enter the user names you would like to use and the passwords that correspond with each user name.  Save the table and place it in the Bin folder of your project.  Next, code the following into your project:

 

Dim mypath = Application.StartupPath & "\db1.mdb"

Dim mypassword = ""

Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)

Dim cmd As OleDb.OleDbCommand

Dim FailedCount As Integer

 

 

Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click

        'search the user database for access authorization

        If txtUsername.Text.Trim = "" Then

            MessageBox.Show("Please fill your User Name !", "Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            txtUsername.Focus()

            Exit Sub

        End If

 

        If txtPassword.Text.Trim = "" Then

            MessageBox.Show("Please fill your Password !", "Password", MessageBoxButtons.OK,MessageBoxIcon.Exclamation)

            txtPassword.Focus()

            Exit Sub

        End If

 

        Dim sql = "SELECT UserName ,Password FROM Users WHERE UserName='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"

 

        cmd = New OleDb.OleDbCommand(sql, conn)

        conn.Open()

        Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader

 

        Try

            If dr.Read = False Then

                MessageBox.Show("Authentication failed...")

 

                FailedCount += 1

 

                If FailedCount >= 3 Then

                    MessageBox.Show("Sorry, too many error !", _

                               "Password", MessageBoxButtons.OK, _

                               MessageBoxIcon.Exclamation)

                    'Close application

                    End

                Else

 

                    txtUsername.Clear()

                    txtPassword.Clear()

 

 

                    MessageBox.Show("Invalid User Name or Password !", _

                                 "Password", MessageBoxButtons.OK, _

                                 MessageBoxIcon.Error)

                End If

            Else

                MessageBox.Show("Login successful...")

 

 

                Dim frmMainMenu As New frmMainMenu

                frmMainMenu.Show()

            End If

        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

 

        conn.Close()

 

    End Sub

 

Placing the date and time into a status bar panel in Vb.net - Matt

 

Create a status bar on your form

Create two panels within the status bar

In the toolbar, click Components, and drag the timer to the form

Click on the timer and enter the following code:

 

    Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed

        Dim dtt As DateTime = DateTime.Now

        Dim stbTgl As String

        Dim sMsgW As String

 

        'Show Date & Time in Status Bar

        sMsgW = dtt.ToLongTimeString

        stbTgl = dtt.ToShortDateString

        StatusBar1.Panels(1).Alignment = HorizontalAlignment.Right

        StatusBar1.Panels(1).Text = sMsgW

        StatusBar1.Panels(0).Alignment = HorizontalAlignment.Right

        StatusBar1.Panels(0).Text = stbTgl

    End Sub

 

Fall 2005

 

Why reinvent the wheel? – Shane

These sites provide great coding examples or information for free that you may be able to help you.

 

http://www.hotscripts.com

http://www.freevbcode.com/

http://www.aspfree.com/

http://www.freeperlcode.com/

http://www.codeproject.com/

http://www.codebeach.com/

http://www.codeguru.com/

http://www.codetoad.com/

http://freshmeat.net/

 

Troubleshooting Crystal Reports - Ryan

 

If you enter new new data within your database and upon running your reports and it is not updating the new data that has been entered you need to check the location.  To do this you must right click on your Crystal Report and select the database and set location to the proper database.  I found that this works the majority of the time.  In the case that this does not fix the problem, the only method I found of fixing this was to delete the current Crystal Report, not the VB form in which the Crystal Report is located, but just the report and re-create it.

 

Code for hiding the current screen and opening a new one without showing all of them in the background - Ryan

Dim Form6 As New Form6     (Form you want to open)

Form6.Show()

Dim Form2 As New Form2   (Form you are leaving and wanting to hide)

Me.Hide()

VB.Net Tabs - Pamela

When setting tabs in VB.Net it is important to remember that if you have things in a group box that you must set the tab for the group box as well as for the controls you want the tab to stop at.

 

Access Database and VB.Net

When setting up the connection to the Access Database in VB.Net.

1.      Go to the Data Tab on the Toolbox Tab.

2.      Double Click on OleDbDataAdapter.

3.      Click Next in the Data Adapter Configuration Wizard.

4.      Click New Connection.

5.      Go to Provider tab and Click on Microsoft Jet 4.0 OLE DB Provider and click Next.

6.      On the Connection tab type in the path or file name or click the button with the … and find the path and file name for the database.

7.      Click Test Connection, if the connection is successful then click Ok, if not go back and make sure your path and file name are correct.

8.      Back in the Data Adapter Configuration Wizard the path and file name should show up in the box and click Next.

9.      On the next page make sure that USE SQL Statements is highlighted and then click next.

10.  On the next page Click Query Builder, this will take you to a screen that will have the names of the tables on it, do only one table at a time to avoid any confusion. 

11.  You will be able to check either all fields if you want all fields the have the queries built for them or just the ones you want.

12.  Click OK and you will be brought back to the Query Builder Screen.

13.  Click Next and this will take you to a screen to show that it has created the queries for all of the fields.  If any do not get build, check to make sure that you have a primary key identified in your database and run the Wizard again.

14.  Click Finish, this will automatically add a Data Adapter and a Data Connection to your page.

 

How to Generate Crystal Reports and View Them - Densen

First make sure that the database you want to report on is in your VB.Net folder.

 

With your VB project open, click on File and select Add New Item.  Scroll down until you see Crystal Report in the templates, select it and give it a name.  [Select register later on the Crystal Reports screen].  In this example, we are going to use the Report Expert and Standard so select OK.  The next screen to pop up will ask you to select the data you want to report on.  Click on the (+) on database files and a screen will pop up.  This is where you find that database that you put in the VB folder and click Open.  Under database files, click the (+) next to tables; highlight the table you want to use and click Insert Table. Use the Next button to scroll through the tabs.  The Fields tab lets you select the fields you want to report on.  You can also use the Group tab to group by certain fields.  You can fiddle with this stuff on your own time!  The Style tab at the end allows you to select a report format and add a title.  After tweaking, click Finish and your report is created.  If you want to change formatting later, just right click on the form.

 

Now you have to link the report you just made to your project.  To do this, go to file and Add New Item.  Select Windows Form and give it a name.  Next, you have to add a Crystal Reports Viewer control to the form you just created.  Go to the toolbox and scroll all the way to the bottom, select the Crystal Reports Viewer and add it to your form.  Open it up to about the size of the form so you can see it.  Set the anchor property to anchor all four edges and the Display Group Tree property to false.  Use whatever naming conventions you use to name the viewer.  Also under properties, select Report Source and click browse.  Find the report you created for this viewer and select it.  Your report is now linked to your viewer and it will show your report.

 

!!!ATTENTION!!!

 

If you move your program [let’s say from your home computer to a pen drive] you have to back to the report (Not the report viewer), right click, go to database and set location.  It will show where the current database is set at and on the right you find the one on your pen drive to replace it with.  Click replace and you are good to go.

 

Spring 2005

 

Turning the cursor to an hourglass - Micah

 

Put this bit in before the processing starts

       'make cursor stall

       Me.Cursor = Cursors.WaitCursor

 

And then change it back upon completion

       'cursor restore

       Me.Cursor = Cursors.Default

 

How to get the Update or Save button to work - Joshua

'Activate the update

If Me.BindingContext(DsSalesman1, "Salesman").Position = 0 Then

Me.BindingContext(DsSalesman1, "Salesman").Position = (Me.BindingContext(DsSalesman1, "Salesman").Position + 1)

Me.BindingContext(DsSalesman1, "Salesman").Position = (Me.BindingContext(DsSalesman1, "Salesman").Position - 1)

Else

Me.BindingContext(DsSalesman1, "Salesman").Position = (Me.BindingContext(DsSalesman1, "Salesman").Position - 1)

Me.BindingContext(DsSalesman1, "Salesman").Position = (Me.BindingContext(DsSalesman1, "Salesman").Position + 1)

End If

 

This is an example of how you get labels to accumulate

Place this under the calculate button

Dim decDailySales As Decimal

Dim decTotalProfit As Decimal

'Adds the Today's Sales to the Year-to-date Sales and keeps a running total

decDailySales = CDec(txtDailySales.Text)

decTotalProfit = decDailySales + lblTotalProfit.Text

lblTotalProfit.Text = decTotalProfit

 

 

To use SQL in VB.NET - Micah

 

File | Add New Item | Class |  name it Global.VB

 

Set up your globals like so:

 

    'globals for data import

    Public cur As New Form

    Public strSQL As String

    Public con As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\Documents and Settings\

     All Users\mydatabase.mdb;Persist Security Info=False;" 'put this all on one line!

    Public oledbcon As New OleDbConnection(con)

    Public da As OleDbDataAdapter

    Public ds As DataSet

    Public logda As OleDbDataAdapter

    Public logds As DataSet

    Public ask, password, useridhold As String

    Public i As Integer

 

These will make sense when you see how they are used.  Note where I put the Access file.  This is a file that is common to any XP/2000 computer and the lab computers allow you to save work there ... very handy.

 

Now open the code of the form that will be handling your Access database I/O

 

It needs the following bit of code pasted at the VERY top to bring the database online:

Imports System.Data.OleDb

 

Now you are ready to add, update, and delete

 

            'build SQL string and run for an ADD

            strSQL = "INSERT INTO Event" & _

            "(EventID, Category,Income,Machine,TimeAndDate)VALUES " & _

            "('" & TextBox1.Text & "'," & _

            "'" & TextBox2.Text & "','" & TextBox3.Text & "', " & _

            "'" & TextBox4.Text & "','" & TextBox6.Text & "')"

            oledbcon.Open()

            Dim cmd As New OleDbCommand(strSQL, oledbcon)

            cmd.ExecuteNonQuery()

            oledbcon.Close()

 

buried underneath all those quotation marks are the SQL statements that you fondly recall learning in Dr. Hendrix's class.

 

Here's how it would look normally:

           

INSERT INTO Event (EventID, Category,Income,Machine,TimeAndDate)VALUES 

            ('2223 ','Sales', '3.45', 'Machine', 'TimeAndDate )"

 

See how that works? Good because now you are on your own to sort out the ones below.  A word of caution: You are only building up the SQL statement as a string in .NET so all those great debugging tools, you rely on, won’t be helping you compose these statements correctly.  I found that going outside of .NET, running the program, letting it crash on my bad SQL statement, and then reading the error statement on the message box of death was very helpful.  The error it gives is usually very specific about where the problem is.

 

            'SQL Delete statement

            oledbcon.Open()

            strSQL = "DELETE FROM Event " & _

            "WHERE EventID = '" & TextBox1.Text & "' "

            Dim cmd As New OleDbCommand(strSQL, oledbcon)

            cmd.ExecuteNonQuery()

            'MsgBox("Data Was Successfully Delete From DataBase !", MsgBoxStyle.Information, "Sales System")

            oledbcon.Close()

 

           

            'SQL Update statement

            oledbcon.Open()

            strSQL = "UPDATE Event SET " & _

            "Category = '" & TextBox2.Text & "', Income = '" & TextBox3.Text & _

            "', Machine = '" & TextBox4.Text & "', TimeAndDate = '" & TextBox6.Text & _

            "' WHERE EventID = '" & TextBox1.Text & "'"

            Dim cmd As New OleDbCommand(strSQL, oledbcon)

            cmd.ExecuteNonQuery()

            'MsgBox("Data Sales Saved Successfully !", MsgBoxStyle.Information, "Sales System")

            oledbcon.Close()

 

 

This is the code for a multi user password.  Desiree

 

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        'search the user database for access authorization

        DataSet11.Clear()

        dbProject.SelectCommand.Parameters("User_Name").Value = txtUser.Text

        dbProject.SelectCommand.Parameters("Password").Value = txtPass.Text

        dbProject.Fill(DataSet11)

        If DataSet11.Tables("User").Rows.Count = 0 Then

            MessageBox.Show("User not Registered", "Unauthorized User", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand)

        Else

            Dim frmCRUD As New frmCRUD

            frmCRUD.Show()

        End If

 

    End Sub

 

 

How to check and change the tab order on your screens - Christy

 

Make sure that you are on the design view of your screen and click on view on the menu bar. Then choose tab order.  This shows which order everything is in.  If you want to change the order just click on the numbers, and put in the order that you want. 

 

 

Crystal Reports troubleshooting - Cynthia

If you get an error when you run your report that states:"buffer too small, or missing null byte"

 

Go check your path structure,  Crystal Reports seems to have trouble connecting to a path structure that has any spaces in it anywhere.  It may also be helpful to try to not bury your project too many layers deep in the path.

 

ex:  D:\Project\SeniorProject (this would be for a zip drive)

 

This code will clear text fields – Matthew P

 

txtAuthor.Clear()

txtISBN.Clear()

txtTitle.Clear()

End Sub

 

This code will move to the last record – Matthew P

 

Try

            With Me.BindingContext(DsBooks1, “Books”)

            .Position = .Count - 1

            DisplayRecordPosition()

End With

Catch

            ‘ Ignore any errors during navigation

End Try

END SUB

 

This code will display the next record – Matthew P

 

Try

            Me.BindingContext(DsBooks1, “Book”).Position += 1

            DisplayRecordPosition()

 

Catch

            ‘ Ignore any errors during navigation

End Try

END SUB

 

Example for Webpage Button code - Michael

This code will go on your screen button label webpage. This code will access your webpage off your Zip disk. When clicking on the webpage button, you can view your webpage online.

Shell("Explorer E:\Homepage\Welcome To My Webpage.htm")

 

If anyone is considering generating your own reports from scratch, here is a little help.- Micah

 

You can create your own evenly spaced columns of text in a COBOL sort of way using a rich text box.Put a rich text box on your project and set the properties to:

 

ScrollBars - ForcedBoth

Font - Courier New (or another font of fixed pitch)

Wordwrap - False

 

And here is example code for populating it:

------

        Dim DataPos As Short = 0

        Dim holder As String

        RichTextBox1.Text = " "

 

        While DataPos < 40

 

            holder = DataSet11.Tables(0).Rows(DataPos).Item("EventID") & "     

            holder = holder.Insert(15,DataSet11.Tables(0).Rows(DataPos).Item("Category")) & "    "

            holder = holder.Insert(30,DataSet11.Tables(0).Rows(DataPos).Item("Income")) & "     "

            holder = holder.Insert(45,DataSet11.Tables(0).Rows(DataPos).Item("Machine")) & "    "

            holder = holder.Insert(60,DataSet11.Tables(0).Rows(DataPos).Item("Time"))

            holder = holder.TrimEnd

            If (DataSet11.Tables(0).Rows(DataPos).Item("Time") >DateTimePicker1.Text) And

                (DataSet11.Tables(0).Rows(DataPos).Item("Time") <DateTimePicker2.Text) Then

                RichTextBox1.Text = RichTextBox1.Text + (vbCrLf & holder)

            End If

 

            DataPos = DataPos + 1

        End While

------

 

What’s going on here:

 

The insert function puts one string into another at a given position: holder.  Insert(15, "Insert this at position 15")

 

holder is the string that is being built up, 15 is the number of character positions from the left, the text within the quotation marks is the the string to be inserted. Above I put a reference to a table value in this position.

 

vbCrLf starts a new line

vbTab inserts a tab but these are of limited use ... use the insert function instead

 

Good stuff on vb.net.  It looks pretty good. - Cynthia

 

http://www.homeandlearn.co.uk/

 

Here is a good website to look at for visual basic.net - Michael Parnell

 

http://www.vbip.com/

 

To download some free visual basic tools

 

http://www.myzips.com/listings/VB-Components/Programming/46/

 

The forums allow for searching for applicable postings and articles. Postings range from beginner to expert. – Matt Parker

http://www.vbcity.com/forums/

http://www.gotdotnet.com/community/messageboard/Home.aspx

 

Problems getting program to exit out of run time on a VB program in Visual Studio.Net – Chris L

 

Insert the word End into the code for the button you want to use to close the program to make the program exit.

 

Example:

 

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click

        Me.Close()

        End

End Sub

Open your data base from your form - Thomas

Type - System.Diagnostics.Process.Start then type where your database is located, and finally your database name.

Example:  System.Diagnostics.Process.Start("C:\Documents and Settings\OC Himura\My Documents\Senior Project\Database\Multimedia.mdb")

Code for printing in VB.- Michael

 

Private Sub btnPrint_Click

 

'Print the report using Print Preview

 

    ppdPreview.Document  = prtDocument 

    ppdPreview.ShowDialog( )

End Sub

 

Code for  updating - Matthew

 

If mblnIsDirty Then

   If  MessageBox.Show ("Do you want to save the changes?", "Books", _

      MessageBoxButtons.YesNo, MessageBoxIcon.question) = DialogResult.Yes Then

            Try

                dbRnR.Update(DsBooks1, "Books")

             Catch

                   MessageBox.Show ("  Error saving the file", "Books") 

              End Try

            End If

          End If

End Sub

           

 

 

Implementation of QuickWhere component for searching into databases. - Kevin

 

     Think of a WHERE clause as a tree with one or more branches; each branch has one or more leaves and each leaf is one WhereItem. The branches are presented by the WhereClause class, with each single branch (WhereClause) having sub-branches.

     The WhereItem class generates the primary WHERE clauses and consists of two values: the properties value  and value2. This allows you to use the BETWEEN condition in the WHERE clause. When one of the values of a BETWEEN condition is left blank, WhereItem converts it into the proper GreaterOrEqual or LessOrEqual condition. If the value is  IS NULL both properties are ignored. 

     You can use the basic classes WhereItem and WhereClause to create a WHERE clause with the level of complexity you need. For example:

 

'the default WhereCondition is WhereCondition.EqualTo

'the default ValueType is TypeOfValues.StringType

 

With wiFirstName

     .FieldName = "FirstName"

     .TableName = "Personnel"

     .Value = "John"

End With

 

With wiLastName

     .FieldName = "LastName"

     .TableName = "Personnel"

     .Value = "son"

     .WhereCondition = WhereConditions.EndsWith

End With

 

With wiDepartment

     .FieldName = "DepartmentID"

     .TableName = "Departments"

     .Value = "9"

     .ValueType = TypeOfValue.NumericType

End With

 

'the default Operators is Operators.AndOperator

 

With wiSale

     .FieldName = "Sale"

     .Value = "15000"

     .TableName = "Sales"

     .ValueType = TypeOfValues.DateType

     .WhereCondition = WhereConditions.Between

End With

wcSearchBySale.Add(wiSale)

wcSearchBySale.Add(wiSaleDate)

 

wcFinalSearch.Add(wcSearchByName)

wcFinalSearch.Add(wcSearchBySale)

 

MsgBox(wcFinalSearch.GetSql(Operators.OrOperator)

 

The generated WHERE clause is:

 

(([Personnel].[FirstName] = "John") AND ([Personnel].[LastName] LIKE "*son"

   AND ([DepartmentID] = 9)) OR

(([Sales].[Sale] >=15000) AND ([Sales].[SaleDate] BETWEEN #01/10/87# AND

   #25/10/87#))

 

Linking/Binding your individual TextBoxes to MS Access using VB.NET - Justin H

**Please note... you must create an Ole DB connection and import/create a Data Adapter into your form before doing this.

for VB.NET: "Bind your TextBox Fields to appropriate fields in Microsoft Access"

Goto: TextBox Properties.

1. Under the "Data" segment of your TextBox Properties, look for "(Data Bindings)"

2. click the "+" sign to expose additional properties of "(Data Bindings)"

3. Click "Text" Property

4. Click the down arrow to the right of the "Text" Property (A drop down list of your tables should appear).

5. Click the "+" sign next to your dataset name to expose your Table.

6. Click the "+" sign next to your table to expose your fields.

7. Select the appropriate field in your table for which you want your TextBox data to bind with.

 

 

Fall 2004

 

VB.Net and Access - Charlotte

 

When creating forms in .Net; there is a very easy way that creates the form using the information from your database. 

Right click on your project name

Select Add

Select Add Windows Form or Add New Item

Select Data Form Wizard

And Rename the form

Complete the wizard step by step

In order to do this, you must link your database to vb first

 

How to print reports:

ALWAYS use crystal reports

This is by far the simplest way to produce output from your project.

 

To find information on coding and example code, the best book to use would be

Programming in Visual Basic.NET by Julia Case Bradley and Anita C. Millspaugh.

This would be the first (blue) book used in Mr. Fendley's .Net class.

 

Various VB.net Resources – Sushma

 

http://www.vbdotnetheaven.com/Code/Jun2003/2007.asp

This site is very helpful for Crystal Reports.

http://msdn.microsoft.com/msdnmag/issues/02/05/Crystal/default.aspx

 

Advancing Programming Using Visual Basic.Net, Julia Case Bradley & Anita C. Millspaugh

            This book gives information about the following:

a)      Obtaining data using Data Adapter

a.                   Set up a connection. A connection establishes a link to a data source, which is a specific file/server.

b.                  Set up a data adapter. A data adapter handles retrieving and updating the data. It also creates a DataSet object.

c.                   Add controls to your form and set properties to bind the controls to the fields in the DataSet object.

d.                  Write some VB code to fill the DataSet object.

b)      Displaying Data in Grid

a.                   Select a DataGrid from the toolbox and add it to your form.

b.                  Name the DataGrid, e.g. dgrEmployee1

c.                   Set the DataSource property, e.g. DsEmployee1

d.                  Set the DataMember to your table name, e.g. if your table name is Employee it will be Employee.

e.                   In the Form_Load event procedure, use the data adapter’s Fill method to fill the dataset.

f.                    Code will be like this:

               daEmployee.Fill(DsEmployee1)

c)      Populating Combo Box with Data

a.                   Set the DataSource property. This connects to the dataset.

b.                  Set the DataMember property. This connects to the specific field name for the data that you want to display in the list.

c.                   After the property is set, drop down the Properties list for Source and select the dataset name. Then drop down the list for Display Member property; it will show the field names in the dataset from which you can select.

d.                  When you run your program, the list automatically fills with the values from the selected field.

            Note: You must use the FILL method for the dataset to load the list.

d)      Creating a Data Tier- Step by Step

a.                   Add a component for the Data Tier

b.                  Code the component

c.                   In the Form_load event procedure write the code to retrieve the dataset and bind to the DataGrid.

           Note: You cannot do this in design time.

 

Programming Visual Basic.Net, Francesco Balena

        This book gives information about the following:

a)      Sorting rows

a.                   Set the AllowSorting property to True

b.                  Set the SortExpression property for one or more columns to a suitable string. This can be done from the Column page of the Property Builder page

c.                   Bind the DataGrid to a DataView object and set its Sort property accordingly.

b)      Binding web form controls

a.                   To bind a List control the first thing to do is to assign the data source object to the DataSource property.

b.                  To fill a list control it must be assigned to an ADO.Net object, such as, Data Reader, Data Table, Data View etc.

c)      SQL queries for binding data to the form

a.                   Generate the Data Adapter configuration

b.                  Create a connection to the database using the wizard

c.                   In the Generate the SQL statements Field, you can either let the wizard automatically create a query for you or you can also create your own query.

d)      Selecting only the required columns from the database.

a.                   In the Property Builder, you can go to the column field and Deselect ‘Create columns automatically at run time’.

b.                  On the column list Select the required columns and add to the Selected columns field

c.                   Click OK

d.                  You can also set the SORT property in Property Builder

 

A VB.Net website – Charlette

 

This website has code samples for the following:

Loading another form

MDI Forms

Databinding Basics

Executing SQL Queries on a bound source

Flat Files

ADO.Net sample

Printing

 

http://www.geocities.com/chuckeasttom/vb/code.htm

 

 

 

Spring 2004

 

 When using VB.net; Heres the Code when you want to go from form to form. Jonathan

 OK = True

Me.Show()

Dim FormName As New Form Name

FormName.Show()

 

When using VB.Net and Access; Here how to make a connection to a database. - Jonathan

 Open Form

Click on Sever Explorer

          Right Click on Add Connection

Click Provider Tab

         (Microsoft Access Only)

                Microsoft Jet 4.0 OLE DB Provider

Click Next

Select Database Name

          (By Clicking the button next to the blank box )

-Find Database

-Open Database

Make sure to test connection before clicking the OK button

Click OK button when finished

 

Adding a link to your webpage in VB.Net - Chris

Code a button, or link to this:

System.Diagnostics.Process.Start("http://www.google.com")

 

How to Calculate - Seth

        Dim intQty1 As Integer

        Dim decPrice1 As Decimal

        Dim decTotal1 As Decimal

 

        intQty1 = CInt(txtQty1.Text)***txtQty1 was pulled from a field an converted to an integer***

        decPrice1 = CDec(txtPrice1.Text))***decPrice1 was pulled from a field an converted to an decimal***

 

        decTotal1 = intQty1 * decPrice1***This is were the calculation is performed***

 

        txtTotal1.Text = FormatCurrency(decTotal1)***This is were the calculation will be entered back into the field***

 

Here are some websites to check out for VB and VB.NET code: - Kathy

 

                        www.ProgrammersHeaven.com

                        www.codeproject.com

                        www.a1vbcode.com

                        www.freevbcode.com

                        www.planet-source-code.com/vb

 

 

You have to get a free membership. It allows you to search for things concerning not only VB6 and VB.NET- Jared

http://www.vbcity.com

 

HOW TO ACCESS YOUR SQL SERVER IN VB.NET - Kathy

Open VB.NET

Click Projects Tab

Click New Project at bottom of page

Make sure Visual Basic Projects is selected

Select Windows application

In the Name box type in the Name of your project (Ex. Charlotte’s Circle)

In the Location box click the drop down arrow and select the drive that you want to save in. (Hint: If you are saving on a zip disk make sure that your disk is in the drive and select D://. DO NOT WRITE YOUR PROJECT NAME AFTER THE PROMPT. VB.NET will automatically name your project from the name box.)

Click ok

Click the Server Explorer Tab on the left side of your page

If it is not showing there select it from the View menu

When you expand the Server Explorer click the Connect to Server icon

When the Add Server screen pops up type in UAMCIS in caps

Click ok

You should see the UAMCIS server listed in the Server Explorer

Expand the UAMCIS node and SQL Server should be listed

Expand this and you should see a listing of all the databases.

If you click on your database it will show your tables and views.