TnTinMN 418 Practically a Master Poster

Give this code pattern a try:

Imports Microsoft.Office.Interop

Public Class Form1

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

      ' When working with ComObjects like a WordApp or any of its parts like Docement, Range etc.
      ' define a variable for each part.  

      ' I follow the Single Dot Rule when accessing the component classes.
      '     i.e. donot code doc.BooKmarks("Contact1").Range.Text 
      '     (Bookmark class and Range Class referenced)
      '
      ' This can create unbound references to a ComObject that will cause Word to remain running as 
      ' a hidden application.

      Dim wordapp As Word.Application = CType(CreateObject("Word.Application"), Word.Application)

      ' load a document template file

      Dim doc As Word.Document = wordapp.Documents.Add("D:\My Documents\temp\Word Example Bookmark Template.dot")

      Dim bookmark As Word.Bookmark = doc.Bookmarks("Contact1")

      Dim rng As Word.Range = bookmark.Range
      bookmark = Nothing ' done with bookmark, so release it

      rng.Text = "some text"
      rng = Nothing ' done with this range, so release it

      doc.SaveAs("D:\My Documents\temp\Word Example Bookmark Template.doc", Word.WdDocumentType.wdTypeDocument)
      doc.Close(False)

      doc = Nothing ' done with doc, so release it
      wordapp.Quit()
      wordapp = Nothing 'done with app, so release it
   End Sub
End Class
TnTinMN 418 Practically a Master Poster

For you first question regarding Process. "Process.Start" is a shared function that returns the started process. The correct syntax would be:

Dim NewProcess As Process ' No New keyword
If Attachment2TextBox.Text <> "" Then NewProcess = Process.Start(Attachment2TextBox.Text)

For you second question, I am not going to re-invent the wheel, but rather point you to Microsoft's code example on this. It provides a nice description of how to do this.

The root page for their samples is:

All-In-One Code Framework

TnTinMN 418 Practically a Master Poster

Only if the control is explicitly made public in Form2. By default new controls added through the designer are private (as they should be!), and in a code review I'd question making them public.

I'm not looking to jump into the fray; just providing some information.

For C# the default control access modifier is "private", for VB the default access modifier is "Friend" (internal).

TnTinMN 418 Practically a Master Poster

deceptikon,

Warning - I'm on my soapbox again

It is not your fault that MS has always tried to make VB.Net compile whatever garbage it is thrown.

"Option Strict" should never have been an option at all, all they needed to do was provide an code attribute syntax to allow late binding for when it is absolutely necessary.

I really hate their Anonymous Type for LINQ "BS" as well with telling people that have to use it for LINQ with "Option Infer ON". That's another option that I loath as I believe in being very explicit when it comes to coding. I really get a kick out of the many VB examples in the documentation that do not hold the company line and show strongly typed LINQ.

Option Explicit On ' declare your variable types
Option Strict On ' no implicit type conversion
Option Infer Off ' inference is just an (hopefully) educated guess as to one's intent.

OK, I'm back on my meds. ;)

Have a nice day.

TnTinMN 418 Practically a Master Poster

I believe you are getting the error due to your use of "+" for string concatonation. Since you have a numerical value (cmbSecurity_Ques.SelectedIndex) in your code, the compiler is treating all of it as a mathematical equation.

Switch to using "&" and change:

cmbSecurity_Ques.SelectedIndex

to:

cmbSecurity_Ques.SelectedIndex.ToString

TnTinMN 418 Practically a Master Poster

You are a welcome.

It was nice to see a well defined problem with all the supporting information.

I should have done this last night, but you are getting a up-vote for knowing how to ask for help.

TnTinMN 418 Practically a Master Poster

Be advised that setting the class style to CS_NOCLOSE (named CP_NOCLOSE_BUTTON in Doogledude's example) will also prevent Alt-F4 from closing the window. You can achieve the same effect while retaining Alt-F4 closure by PInvoking the RemoveMenu function.

   Private Const MF_BYCOMMAND As Integer = 0

   <DllImport("User32")> _
   Private Shared Function RemoveMenu(ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Integer) As Integer
   End Function

   <DllImport("User32")> _
   Private Shared Function GetSystemMenu(ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
   End Function

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Dim hMenu As IntPtr = GetSystemMenu(Me.Handle, False)
      RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND)
   End Sub
TnTinMN 418 Practically a Master Poster

You need an ExpandableObjectConverter.

It's pretty easy to do. :)

Here is the converter:

Public Class DatabasePropertiesConverter
   Inherits ExpandableObjectConverter

   Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object

      If destinationType Is GetType(String) Then
         Return "" ' this prevents the type name from showing up in the property grid
      End If

      Return MyBase.ConvertTo(context, culture, value, destinationType)

   End Function
End Class

Now to implement it

   <TypeConverter(GetType(DatabasePropertiesConverter))> _
    Public Class DatabaseProperties
    .
    . <ommitted code>
    .

    'add the NotifyParentPropertyAttribute to each sub property
    <NotifyParentProperty(True)> _
    <Category("Connection")> _
    <Description("Host Name/IP address of the server where the database resides.")> _
    <DefaultValue(GetType(String), "")> _
    <DisplayName("Host Address")> _
    <Browsable(True)> _
    <ReadOnlyAttribute(False)> _
    Public Property HostName() As String
        Get
            Return Me.DBHost
        End Get
        Set(ByVal value As String)
            Me.DBHost = value
        End Set
    End Property

    .  **** I corrected the above property from DBUser to DBHost
    . 
    . <do same for other properties>
    .
TnTinMN 418 Practically a Master Poster
TnTinMN 418 Practically a Master Poster

Give this a try:

SearchComand = "SELECT * From LaborHours where Date= #" & Me.DTPDate.Value.Date.ToString(System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern) & "# and EmployeeID=Val(" & EmployeeID.Text & ") and PayrollID=val(" & PayrollID.Text & ")"

This assumes that the DateTime value from Access does not have a time component (usually safe assumption). For Access, you need to bracket the date with "#" characters (i.e. #1/20/2013# for 20 Jan 2013). It needs to be in Microsoft's InvariantCulture.ShortDatePattern (i.e. USA standards) format (mm/dd/yyyy) to ensure that there is no time component.

TnTinMN 418 Practically a Master Poster

I looked at your previous thread and the advice you were given should have worked if it was implemented correctly. So, please show your actual code where you define your Select query. This should be easy to correct for you if we have the relevant information.

Also, what type of database are you using?(SQLServer, Access, Oracle, MySql etc.)

TnTinMN 418 Practically a Master Poster

I can't find "Controls.InvokeRequired" in vb.net2003. I want to write a simple data updating from "Mulitple Thread", but I would like to check whether "Controls" are requied "Invoke" or not.

I can't say for certain as I never worked with Visual Basic .Net 2003 or the 1.1 .Net Framework, but the documentation indicates that the InvokeRequired property did exist in that version.

Control.InvokeRequired Property

Just because .Net 1.1 did not enforce cross-thread checks, does not mean its safe practice.

You mention updating every millisecond. This is not very probable as the paint events alone take longer than that. Also, you have shown a DoEvents (very time consuming and not very safe to throw around haphazardly Click Here) followed by a 250 millisecond thread sleep.

I think you need to get out of panic mode and relax and think about what you need to do and draft a plan of action.

TnTinMN 418 Practically a Master Poster

I believe the OP is concerned about getting the proper SQL Express server name on an unknown installation.

The following code works fine with SQL Express running on the machine. I have never tested it to see if it finds a Network server. When I still had SQLExpress 2005 and 2008 installed, it found both instances.

   Dim csb As New SqlClient.SqlConnectionStringBuilder
   csb.IntegratedSecurity = True
   csb.UserInstance = True

   ' This next line can take a few seconds to complete
   Dim dtSQLServers As DataTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources()

   If dtSQLServers.Rows.Count > 0 Then ' Take 1st entry.  Could loop through all entries if needed
      Try
         Dim ServerName As String = dtSQLServers.Rows.Item(0).Field(Of String)("ServerName")
         Dim InstanceName As String = dtSQLServers.Rows.Item(0).Field(Of String)("InstanceName")
         csb.DataSource = ServerName & "\" & InstanceName
      Catch ex As Exception
         MsgBox(ex.Message)
         Exit Try
      End Try
   End If 'dtSQLServers.Rows.Count > 0

   If csb.DataSource IsNot Nothing Then ' List the available database
      Dim conn As New SqlClient.SqlConnection(csb.ConnectionString)
      Dim cmd As New SqlClient.SqlCommand("Select name From sys.databases", conn)
      Dim da As New SqlClient.SqlDataAdapter(cmd)
      Dim tables As New DataTable
      da.Fill(tables)

      For Each dr As DataRow In tables.Rows
         Console.WriteLine(dr(0).ToString)
      Next dr
   End If
TnTinMN 418 Practically a Master Poster

I don't use either VS2012 or MySql, but based on their support forum, it looks like a lot of people have had issues with this configuration. Do you have the the latest vesion of Connector/Net installed? Based on this: Click Here, the newer releases should offer full VS2012 support.

As a possible workaround, have you tried connecting through ODBC instead?

TnTinMN 418 Practically a Master Poster

Are you using VS2012 Express, if so you may be out of luck.

Click Here

TnTinMN 418 Practically a Master Poster

What's declaring it partial do as opposed to your initial?

VB.Net creates a Class MyApplication within the "My" namespace. Since I was extending that class (my code is added to the overall Class definition) and only one of the Class Definitions can omit the Partial keyword, it is proper to use the Partial keyword. You can have many Partial Class segments.

For more info, Click Here.

@daniwan

Sorry if I'm not as on topic as maybe I should be but isn't there a static object decleration in VB? Can you not just define a static class / object with the method and the members then invoke the method which would populate the members, any class or object should then be able to read from the same static name space / scope.

That is essentially what Ancient Dragon presented. All elements of a Module are static. For more info see: Standard Modules vs. Class Modules

TnTinMN 418 Practically a Master Poster

@TnTinMN - Just curious - is their an advantage to doing this rather than using My.Settings?
It really depends on what you want to do.

My.Settings typically are used to persist a value between runs of an application. You could however, just use them as a global variable definition as long as you did not care if the value was written to disk when you told the app to save them (or you could zero them out before saving).

The OP asked about creating a Global function, so I went this route. I just like the logic of "My.Application.VariableName". The "My" namespace is once of the niceties provided by VB; so, I figure why not use it.

I assumed that the OP's "config.txt" file was generated outside of the application. If not, then definitely a My.Settings route would make more sense.

Options, options, options, to many options. :)

Oops: Just noticed that I forgot the Partial keyword in my original post.

It should have been: Partial Friend Class MyApplication

TnTinMN 418 Practically a Master Poster

The option that I prefer is to extend the "My" namespace. It is designed just for this type of use.

I assumed that the config file only would need to be read once. If this is not the case you can easily modify the logic. Just add this like you would a Class or Module to your code.

 Namespace My
   Friend Class MyApplication
      Private _configvars(0 To 3) As String
      Public ReadOnly Property configvars(ByVal index As Int32) As String
         Get
            If _configvars(0) Is Nothing Then
               ' read config file
               Dim fileReader As System.IO.StreamReader
               fileReader = My.Computer.FileSystem.OpenTextFileReader("config.txt")

               Dim count As Integer = 0
               Do Until count = 4
                  _configvars(count) = fileReader.ReadLine()
                  count = count + 1
               Loop

            End If
            Return _configvars(index)
         End Get
      End Property 'configvars
   End Class
End Namespace 

Now to retrieve your values: My.Application.configvars(0)

P.S.: Glad to see that I'm not the only left using the old array declaration syntax (0 to something). :))

TnTinMN 418 Practically a Master Poster

I think this pattern should work for you. I'm still learning this XML stuff.

   ' create a named datatable
   ' content is irrelevant
   Dim dt As New DataTable("fredsfamily")
   Dim r As DataRow
   With dt
      .Columns.Add("Name")
      r = .NewRow : r(0) = "wilma" : .Rows.Add(r)
      r = .NewRow : r(0) = "pebbles" : .Rows.Add(r)
   End With

   ' Instead of writing directly to a file
   ' write to a stringbuilder

   Dim sb As New System.Text.StringBuilder(500)
   Dim writer As New IO.StringWriter(sb)

   ' make sure you include the schema definition and not just the data
   dt.WriteXml(writer, XmlWriteMode.WriteSchema)


   ' Now the we have the Table XML in the stringbuilder
   ' create a XmlDocument and load it from the stringbuilder
   Dim doc As New Xml.XmlDocument()
   doc.LoadXml(sb.ToString)

   ' Now we can modify the documents content
   ' I adding a CDataSection to hold the text
   Dim el As Xml.XmlCDataSection = doc.CreateCDataSection(tbSomething.Text)
   doc.DocumentElement.AppendChild(el)

   doc.Save("test.xml") ' Now write it to a file


   ' *** Now to reverse the process and read the XML file
   tbSomething.Text = String.Empty

   ' The DataTable is easy.
   Dim dt2 As New DataTable

   dt2.ReadXml("test.xml") ' that is it :)

   ' The to retrieve the text we embedded in the file
   'I'm using the Xml.Linq stuff for this as it is a bit easier to code than XPath stuff
   ' Load a document
   Dim doc2 As System.Xml.Linq.XDocument = XDocument.Load("test.xml")
   ' Since we have only one CData
   Dim cdatalist As List(Of Xml.Linq.XCData) = doc2.DescendantNodes.OfType(Of XCData)().ToList()
   ' We should have retrieved 1 CData section into our list …
TnTinMN 418 Practically a Master Poster

Perhaps use a checkbox with a button appearance instead?

Public Class Form1
   Private WithEvents chkButton As New CheckBox _
            With {.Appearance = Appearance.Button, _
                  .CheckState = CheckState.Unchecked, _
                  .Location = New Point(10, 10), _
                  .Size = New Size(150, 25), _
                  .TextAlign = ContentAlignment.MiddleCenter, _
                  .Text = "I'm really a checkbox", _
                  .Parent = Me}

   Private Sub chkButton_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkButton.CheckedChanged
      If chkButton.Checked Then
         MsgBox("I'm Depressed")
      Else
         MsgBox("I'm Up")
      End If
   End Sub
End Class
Ancient Dragon commented: good idea :) +14
TnTinMN 418 Practically a Master Poster

Perhaps using a TimeSpan instead of a DateTime will give you the effect you are looking for?

Public Class Form1

   Private WithEvents tmCountDown As New System.Windows.Forms.Timer With {.Interval = 1000}
   Private tsStartTime As TimeSpan
   Private lblCountDown As New Label With {.Location = New Point(10, 10), _
                                           .AutoSize = True, _
                                           .Font = New Font("Deja Vu Sans", 14, FontStyle.Regular, GraphicsUnit.Point), _
                                           .ForeColor = SystemColors.WindowText, _
                                           .TextAlign = ContentAlignment.MiddleCenter, _
                                           .Parent = Me}

   Private OneSecond As New TimeSpan(0, 0, 1)

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

      ' Set these durations to whatever is needed
      Dim Days As Int32 = 0
      Dim Hrs As Int32 = 0
      Dim Mins As Int32 = 0
      Dim Secs As Int32 = 1
      Dim MilliSecs As Int32 = 0
      tsStartTime = New TimeSpan(Days, Hrs, Mins, Secs, MilliSecs)
      DisplayTime()
      tmCountDown.Start()
   End Sub

   Private Sub tmCountDown_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmCountDown.Tick
      tsStartTime = tsStartTime.Subtract(OneSecond)
      DisplayTime()
      ' Stop CountDown ?  If so, uncomment next line
      'If tsStartTime.Ticks = 0 Then tmCountDown.Stop()
   End Sub

   Private Sub DisplayTime()
      If tsStartTime.Ticks < 0 Then
         lblCountDown.BackColor = Color.Yellow
      Else
         lblCountDown.BackColor = SystemColors.Window
      End If
      lblCountDown.Text = tsStartTime.ToString.Replace("."c, ":"c)
   End Sub
End Class
TnTinMN 418 Practically a Master Poster

Is the button a Microsoft Forms 2.0 Object Library CommandButton that has a TakeFocusOnClick property? If so, try setting the property to false.

TnTinMN 418 Practically a Master Poster

I am bored and decided to go into a tutor mode. :)

First off I believe in strongly typed data, so I recommend that you use an Ingredient class.

Public Class Ingredient
   ''' <summary>
   ''' Builds a new ingredient from a comma delimited source string 
   ''' </summary>
   ''' <param name="Source">ex: "150, Flour, Grams"</param>
   Public Sub New(ByVal Source As String)
      ' split the string into its parts
      Dim parts() As String = Source.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)

      If parts.Length <> 3 Then 'there should only be 3 parts
         Throw New ArgumentException("Invalid source string:  " & Source)
      End If
      Try
         _Quantity = CSng(parts(0)) 'convert string to single
      Catch ex As Exception
         Throw New ArgumentException("Invalid source string quanity:  " & parts(0))
      End Try
      _Name = parts(1)
      _Units = parts(2)
   End Sub

   Private _Quantity As Single
   Public Property Quantity() As Single
      Get
         Return _Quantity
      End Get
      Set(ByVal value As Single)
         _Quantity = value
      End Set
   End Property 'Quantity

   Private _Name As String
   Public Property Name() As String
      Get
         Return _Name
      End Get
      Set(ByVal value As String)
         _Name = value
      End Set
   End Property 'Name

   Private _Units As String
   Public Property Units() As String
      Get
         Return _Units
      End Get
      Set(ByVal value As String)
         _Units = value
      End Set
   End Property 'Units

   ' This will be called by the listbox to provide a string reprepresentation of the the ingredient
   Public Overrides Function ToString() As String
      Return String.Format("{0}, {1}, {2}", _Quantity.ToString, _Name, _Units)
   End Function

End Class

Now to make use of the class. First create a create …

Begginnerdev commented: Great post! But you just did their homework for them. +6
TnTinMN 418 Practically a Master Poster

Now while adding each row,if database have value for caste field,combobox should show that value as default value else no default value should be selected.Thanks in advance.

So if the database value is null (no value set), you want the combobox to reflect this by not selecting one of the values in it's Items list?

In my experience, the datagridview combobox cell behaves this way already if the cell value is null (DBNull.Value). Just set the cell value to the value from your database and it should work. Just make sure that all valid values are defined in the column's Items list or you will get a "DataError". The DBNull.Value should not be added to this list.

Are the rest of the datagridview columns bound to a datasource filled from the same database that "caste" is pulled from? If so, there is no need to add
the additional column. Just include "caste" in the bound colums and change it's celltype in the RowsAdded event handler.

   Private Sub dgv_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles dgv.RowsAdded
      ' Loop through the added rows and change the cell to a DataGridViewComboBoxCell
      For i As Int32 = e.RowIndex To (e.RowIndex + e.RowCount - 1)
         dgv.Rows(i).Cells(dgvComboBoxCellName) = _
            New DataGridViewComboBoxCell With {.Value = dgv.Rows(i).Cells(dgvComboBoxCellName).Value, _
                                               .DataSource = dgvComboBoxItems}
      Next i
   End Sub
TnTinMN 418 Practically a Master Poster

Perhaps something like this:

   ' Since all your items are then same, create a list to use as a common DataSource for each ComboBox
   Dim items() As String = {"Sample 1", "Sample 2", "Sample 3", "Sample 4"}

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      'Since your ComboBoxes are named in a consecutive pattern, we can look up their names in a loop
      Dim cboName As String = String.Empty
      Dim p As Control
      For i As Int32 = 1 To 40
         cboName = "ComboBox" & i.ToString
         p = FindParent(Me, cboName)
         If p IsNot Nothing Then
            CType(p.Controls(cboName), ComboBox).DataSource = items
         End If
      Next
   End Sub


   ' Since the ComboBoxes may be parented in a child control, we need to identify their parent control
   ' a simple recursive search will do the trick
   Private Function FindParent(ByVal source As Control, ByVal name As String) As Control
      For Each c As Control In source.Controls
         If c.Name = name Then
            If c.Parent IsNot Nothing Then
               Return c.Parent
            Else
               Return source
            End If
         Else
            If c.HasChildren Then
               Dim parent As Control = FindParent(c, name)
               If parent IsNot Nothing Then Return parent
            End If 'c.HasChildren

         End If 'c.Name = name
      Next
      Return Nothing
   End Function
TnTinMN 418 Practically a Master Poster

Here is one way to handle it. Add a "Moved" (type Boolean) to the underlying datatable and create to dataviews to act as the datasource for the respective datagridviews.

Public Class Form1
   Private ds As New DataSet

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      ' Make Some Data
      Dim dt As New DataTable("flintstones")
      ds.Tables.Add(dt) ' you indicated that you are using a dataset, so I will also use one
      Dim r As DataRow
      With dt
         ' Add a column for some data:  You don't need to do this as you already have a table of data
         .Columns.Add("data", GetType(String))
         r = .NewRow : r(0) = "fred" : .Rows.Add(r)
         r = .NewRow : r(0) = "wilma" : .Rows.Add(r)
         r = .NewRow : r(0) = "dino" : .Rows.Add(r)
         r = .NewRow : r(0) = "barney" : .Rows.Add(r)
         r = .NewRow : r(0) = "betty" : .Rows.Add(r)
         r = .NewRow : r(0) = "hoppy" : .Rows.Add(r)
      End With

      ' you can add a column to an existing table
      ds.Tables(0).Columns.Add("Moved", GetType(Boolean))
      ' Initially, the added column cells will have a Null value.
      ' We will treat this as false

      ' Create a DataView to act as the datasource for each datgridview

      Dim fromview As New DataView(ds.Tables(0))
      ' Select only False "Moved" rows
      fromview.RowFilter = "[Moved]=False or [Moved] is Null"
      fromview.Sort = "[Data] Asc"
      dgvFrom.DataSource = fromview
      dgvFrom.Columns("Moved").Visible = False
      dgvFrom.SelectionMode = DataGridViewSelectionMode.FullRowSelect
      dgvFrom.ReadOnly = True

      Dim ToView As New DataView(ds.Tables(0))
      ' Select only True "Moved" rows
      ToView.RowFilter = "[Moved]=True" …
TnTinMN 418 Practically a Master Poster

If by "The thread is running in a module" you mean that the method being executed is in a Module, a similar technique can be used. Here is a slightly different version executing a method defined in a module.

Public Class Form1

   Private myParameterInstance As MyParameter
   Dim thrd As Threading.Thread

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      thrd = New Threading.Thread(AddressOf Something.threadMethod)
      myParameterInstance = New MyParameter(New MethodInvoker(AddressOf ToggleForm2))
      thrd.Start(myParameterInstance)
   End Sub

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
      myParameterInstance.Cancel = True
   End Sub

   Private Sub ToggleForm2()
      If Me.InvokeRequired Then
         ' on other thread so call on UI thread
         Me.Invoke(New MethodInvoker(AddressOf ToggleForm2))
         Exit Sub ' on non UI thread
      End If
      Form2.Visible = Not Form2.Visible
   End Sub

   Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      ' Clean up
      If myParameterInstance IsNot Nothing Then
         myParameterInstance.Cancel = True 'shut the thread down
         While thrd.IsAlive
            Threading.Thread.Sleep(500)
            Debug.WriteLine("waiting to end")
         End While
      End If
   End Sub
End Class

' Define a parameter class that contains the info to be passed to the threaded method
' You could just pass a MethodInvoker instance, but I like having a way to cancel a thread
' so I use a Class with a Cancel Property
Friend Class MyParameter

   Public mi As MethodInvoker 'use a simple MethodInvoker to execute a UI method
   Public Sub New(ByVal mi As MethodInvoker)
      Me.mi = mi
   End Sub

   Private _Cancel As Boolean
   Public Property Cancel() As Boolean
      Get
         Return …
TnTinMN 418 Practically a Master Poster

ps. Furthermore, how do I get around the problem of those who do not have access installed on their PC. Obviously they couldnt use the software then.

You don't need Access just the engine installed so you can use the ACE provider or if you prefer the engine directly with record sets.

Microsoft Access Database Engine 2010 Redistributable

TnTinMN 418 Practically a Master Poster

I'm not sure I understand your situation correctly, but UI controls must be manipulated only on the thread that created them. Here is an example that flashes Form2. Note the pattern used with the InvokeRequired.

Public Class Form1
   Private WithEvents bgw As New System.ComponentModel.BackgroundWorker With {.WorkerSupportsCancellation = True}

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      bgw.RunWorkerAsync()
   End Sub

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
      bgw.CancelAsync() ' cancel backgroundworker
   End Sub

   Private Sub ToggleForm2()
      If Me.InvokeRequired Then
         ' on other thread so call on UI thread
         Me.Invoke(New MethodInvoker(AddressOf ToggleForm2))
         Exit Sub ' on non UI thread
      End If

      Form2.Visible = Not Form2.Visible

   End Sub

   Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
      Do
         If bgw.CancellationPending Then
            e.Cancel = True
            Exit Do
         End If
         ToggleForm2()
         Threading.Thread.Sleep(1000)
      Loop
   End Sub

End Class
TnTinMN 418 Practically a Master Poster

Handle the "MediaPlayerEndReached" event to advance the playlist.

TnTinMN 418 Practically a Master Poster

The newer office file formats such as "docx" and "xlsx" are in reality zip packages containing the files that define the contents in "XML" format. These can be created using: Open XML SDK 2.0 for Microsoft Office.

You can view the "XML" content of an office file by renaming it with a ".zip" extension and then opening the compressed folder in explorer or use a utility like "7Zip" to open the office file as an archive directly.

Here is a link to a three part article on creating a Word "Docx" file.
Creating Documents by Using the Open XML Format SDK 2.0

TnTinMN 418 Practically a Master Poster

Other than the obvious, drop the "Shared" keyword, you can use any of the reference syntaxes to the form shown below.

Jim is correct that you will bump into cross thread issues with the FileSystemWatcher events, so I include an example of that technique as well.

Public Class Form1

   'create a delegate template for the method
   Delegate Sub dummy(ByVal caller As TextBox, ByVal text As String)

   ' a method that matches the template defined above
   Sub settext(ByVal caller As TextBox, ByVal text As String)
      caller.Text = text
   End Sub

   Private Shared Sub test()
      My.Forms.Form1.TextBox1.Text = "wilma"
      CType(My.Application.OpenForms.Item("Form1"), Form1).TextBox1.Text = "barney"

      ' Since you are handling events, these events my arrive on a thread other than the UI thread.
      ' To prevent a cross thread error, check if an Invoke is needed
      If Form1.TextBox1.InvokeRequired Then
         ' invoke a call on the UI thread
         Form1.TextBox1.Invoke(New dummy(AddressOf Form1.settext), New Object() {Form1.TextBox1, "dino"})
      Else
         Form1.TextBox1.Text = "fred"
      End If
   End Sub

End Class

Edit: The reference methods shown above assume that you have the "Application Framework" enabled.

kvprajapati commented: Very good suggestion :) +14
TnTinMN 418 Practically a Master Poster

I have seen others claim that you can use either add or addtarget to load a playlist, but those posts are quite old. I have not had any success using those. Howeverthe playlist is just an XML document and it can be easily parsed to extract the filename. Then these filenames can be added to the player's playlist.

  Dim doc As New Xml.XmlDocument()
  doc.Load("Playlist.xspf")

  Dim nsm As New Xml.XmlNamespaceManager(doc.NameTable)
  nsm.AddNamespace("rootns", doc.DocumentElement.NamespaceURI)
  Dim TrackLocations As Xml.XmlNodeList

  TrackLocations = doc.SelectNodes("rootns:playlist/child::rootns:trackList/child::rootns:track/child::rootns:location", nsm)
  If TrackLocations.Count > 0 Then
     AxVLCPlugin21.playlist.items.clear()
     For Each location As Xml.XmlNode In TrackLocations
        AxVLCPlugin21.playlist.add(location.InnerText)
     Next
     AxVLCPlugin21.playlist.play()
  End If
TnTinMN 418 Practically a Master Poster

That is not a question, that is a specification. As stated above, show what you have tried and described what is giving you problems.

TnTinMN 418 Practically a Master Poster

row("Update") = + Update.Value assigns the value of Update to the row's "update" cell.

try this instead:

r("update") = CInt(r("update")) + NumericUpDown1.Value

TnTinMN 418 Practically a Master Poster
TnTinMN 418 Practically a Master Poster

What I can not understand is how that code even runs such that he can see an empty textbox. Only the command variable (cmd) has an instance assigned to it.

Suggest changing:

Dim myDA As SqlCeDataAdapter
Dim myDataSet As DataSet

to:

Dim myDA As New SqlCeDataAdapter
Dim myDataSet As New DataSet
Begginnerdev commented: Good catch, didn't see that one! +6
TnTinMN 418 Practically a Master Poster

It may be a problem with the new version of VLC 2.x.x. (XP32, VS2008)

I had played with this a bit quite a while ago and had it working, but all I got with the newer version installed was a black box. I uninstalled VLC, and deleted the program directory and then installed the last 1.1 version and it works again now.

http://download.videolan.org/pub/videolan/vlc/1.1.9/win32/

Here is a snippet:

  With AxVLCPlugin21
     .CtlVisible = True
     .playlist.items.clear()
     .playlist.add(TempMovieFileName)
     .playlist.playItem(0)

     .Toolbar = True
  End With
TnTinMN 418 Practically a Master Poster

You are either going to have to transform your table into format that databinding can read, or feed the points individually by looping through your table. Since you are using timespans, you will have to transform the timespan to a numeric value. You have been shown before how to do this by using the timespan ticks property to create a new DateTime and then use the the DateTime.ToOADate function.

Here is an example:

Imports System.Windows.Forms.DataVisualization.Charting

Public Class Form1

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

'  Method1 - Add the points

   Dim Chart1 As New Chart
   Chart1.ChartAreas.Add(New ChartArea With {.Name = "myarea"})
   Chart1.Legends.Add("mylegend")
   Chart1.Legends("mylegend").Alignment = StringAlignment.Center


   Dim s1 As New Series
   Dim s2 As New Series


   With s1
      .ChartArea = "myarea"
      .Name = "MC101"
      .ChartType = SeriesChartType.StackedColumn
      .XValueType = ChartValueType.String
      .YValueType = ChartValueType.Double
      With .Points
         .AddXY("J1", 2)
         .AddXY("J2", 3.5)
      End With
   End With

   With s2
      .ChartArea = "myarea"
      .Name = "MC102"
      .ChartType = SeriesChartType.StackedColumn
      .XValueType = ChartValueType.String
      .YValueType = ChartValueType.Double
      With .Points
         .AddXY("J1", 1)
         .AddXY("J2", 4)
      End With
   End With

   Chart1.Series.Add(s1)
   Chart1.Series.Add(s2)

   Me.Controls.Add(Chart1)

   ' Method2 Bound to a table

   Dim Chart2 As New Chart
   Chart2.ChartAreas.Add(New ChartArea With {.Name = "myarea"})
   Chart2.Legends.Add("mylegend")
   Chart2.Legends("mylegend").Alignment = StringAlignment.Center

   Dim dt As New DataTable
   Dim r As DataRow

   With dt
      .Columns.Add("XLables", GetType(String))
      .Columns.Add("MC101", GetType(Double))
      .Columns.Add("MC102", GetType(Double))

      r = .NewRow : r(0) = "J1" : r(1) = 2 : r(2) = 1 : .Rows.Add(r)
      r = .NewRow : r(0) = "J2" : r(1) = 3.5 : r(2) = 4 : …
TnTinMN 418 Practically a Master Poster

Give this a try:
Remember that the column nubering is zero index based (Column4 = index 3)

    Dim sum As Int32 = (From dgvrow In DataGridView1.Rows _
                       Select CInt(CType(dgvrow, DataGridViewRow).Cells(3).Value)) _
                       .Sum()
TnTinMN 418 Practically a Master Poster

As you have learned, that does not work. WinForms are event driven. If you want to handle a click event you have to define the event handler either by attaching the "Handle control.Click" command to the method definition or by using an addhandler statement for each control.

Give this a try. It will attach a Click event handler for all PictureBoxes on the form.

Public Class Form1

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

   Private Sub AddPBClickHandlerToAllPictureBoxesParentByTheFormOrItsChildControls(ByVal cnrl As Control)
      ' Designed to Initially be passed a Form Control instance
      For Each c As Control In cnrl.Controls
         If TypeOf c Is PictureBox Then
            AddHandler c.Click, AddressOf PictureBox_Click
         End If
         If c.HasChildren Then AddPBClickHandlerToAllPictureBoxesParentByTheFormOrItsChildControls(c)
      Next
   End Sub

   Private Sub PictureBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
      If TypeOf sender Is PictureBox Then
         CType(sender, PictureBox).BackColor = Color.Blue
      End If
   End Sub
End Class
TnTinMN 418 Practically a Master Poster

This is what I meant.

'******************************************************************************
'* Sub:     VBMain
'*
'* Purpose: This is main function to start execution 
'*
'* Input:   None
'*
'* Output:  None
'*
'******************************************************************************
Sub VBMain()
    ' **********************
    ' Added this
    '
        ' Ref: http://ss64.com/vb/filesystemobject.html
        ' Get File System Object
        dim fso
        set fso = CreateObject("Scripting.FileSystemObject")

        dim DriveLetter
        DriveLetter = "E"  ' ****** Replace this with the drive letter that would be mounted
        Dim SleepTime 
        SleepTime = 5 ' in Seconds,increase to meet your needs

        On Error Resume Next
        dim USBDrive
        USBDrive = fso.Drives(CStr(DriveLetter))

        while Err.Number <> 0 
            WScript.Echo("Drive " & DriveLetter & ": is not available, Please mount the drive")
            if Err.Number <> 0 then wscript.sleep(SleepTime * 1000) 
            Err.Clear
            USBDrive = fso.Drives(CStr(DriveLetter))
        wend

        set fso = Nothing
        DriveLetter = Nothing

    ' End of the splice
    ' ************************************
    ' Your Original code
    Dim objShell 
    Dim ExitCode

    Set objShell = WScript.CreateObject("WScript.Shell")

' Do the backup
    ExitCode = Backup ("""C:\<filepath> +parameters""")

' done
    Set objShell = nothing
    wscript.quit(ExitCode)
End Sub
TnTinMN 418 Practically a Master Poster

Just a guess, but I think Zick may be a user of google translate or something similar. Hence the odd wording.

Based on this:

Dim query As String
For Each item As ListViewItem In ListView1.Items
query = "Select * from [Calls and Visits$] where AM like '" & item.SubItems(1).Text & "%'"
'execute the query and do something with the results
Next

and this

after finding all the AM in the listview1 to listview2 i will sum all their calls and visits by Month (January to December)

I believe that he wants to search ListView2 for each "AM" entry in ListView1 and compute a yearly "Call" and "Visits" total per "AM" entry.

Perhaps Something Like this:

Private Sub Test()
   ' make some data
   Dim LV1Source As New DataTable
   Dim r As DataRow
   With LV1Source
      .Columns.Add("AM", GetType(String))
      .Columns.Add("Code Name", GetType(String))
      .Columns.Add("Department", GetType(String))
      .Columns.Add("Status", GetType(String))
      r = .NewRow : r(0) = "fred" : r(1) = "Something" : .Rows.Add(r)
      r = .NewRow : r(0) = "barney" : r(1) = "Something" : .Rows.Add(r)
   End With
   Dim LV2Source As New DataTable
   With LV2Source
      .Columns.Add("AM", GetType(String))
      .Columns.Add("Total Calls", GetType(Int32))
      .Columns.Add("Total Visits", GetType(Int32))
      .Columns.Add("Month", GetType(String))
      .Columns.Add("Year", GetType(Int32))
      r = .NewRow : r(0) = "fred" : r(1) = 10 : r(2) = 5 : r(3) = "January" : r(4) = 2011 : .Rows.Add(r)
      r = .NewRow : r(0) = "fred" : r(1) = 10 : r(2) = 5 : r(3) = "February" : r(4) = 2011 : .Rows.Add(r)
      r = …
TnTinMN 418 Practically a Master Poster

Have you tried to merge the logic into your original script file?

TnTinMN 418 Practically a Master Poster

Hi Viper,

I applaud your initiative in deriving your own business week function.

However, I want to warn you that you have forgotten to account for holidays in your computations. This may not be necessary for your application, but if this is for a business application, you should consider the effect of holidays in the computation. This whole issue of weeks-computations can get quite unwieldy as it is affected by locale.

For more info, see: http://en.wikipedia.org/wiki/ISO_8601

TnTinMN 418 Practically a Master Poster

Ok you have a clean intall, but have you installed all the updates?
After installing VS2012 have you checked if there are updates for that as well?

Is there anything in your application that specifically requires .Net 4.5?

If not have you tried setting the Target Framework to 4.0 or even 3.5?

TnTinMN 418 Practically a Master Poster

Great that its working. Corrupted files are a pain, but hey can also be a warning that something may be going wonky with your harddrive. Good time to back up critical files.

It would also be great if you could close this thread by marking it solved.

Thanks

TnTinMN 418 Practically a Master Poster

It's cold and raining and I don't feel like doing the dishes, and this looked like an interesting diversion, so here you go with a dgv Column to countdown from a datetime column. :) Boy how I wish this forum supported putting code in a scrollbox!

Public Class Form1

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Dim dt As New DataTable
      Dim r As DataRow
      With dt
         .Columns.Add("dt", GetType(DateTime))
         r = .NewRow : r(0) = Now.AddMinutes(1) : .Rows.Add(r)
         r = .NewRow : r(0) = Now.AddHours(1) : .Rows.Add(r)
         r = .NewRow : r(0) = Now.AddSeconds(10) : .Rows.Add(r)
         r = .NewRow : r(0) = Now.AddDays(1).AddHours(2).AddMinutes(5) : .Rows.Add(r)
      End With
      DataGridView1.DataSource = dt
      Dim countdown As New DGVColumnDateCountDown
      countdown.ComparisionColumn = DataGridView1.Columns("dt")

      DataGridView1.Columns.Add(countdown)

   End Sub

End Class

Public Class DGVColumnDateCountDown
   Inherits DataGridViewTextBoxColumn
   Public Sub New()
      [ReadOnly] = True
      tmrUpdate.Start()
   End Sub

   Private WithEvents tmrUpdate As New System.Windows.Forms.Timer With {.Interval = 1000}

   Private _PositiveColor As Color = Color.Black
   Public Property PositiveColor() As Color
      Get
         Return _PositiveColor
      End Get
      Set(ByVal value As Color)
         _PositiveColor = value
      End Set
   End Property 'PositiveColor


   Private _NegativeColor As Color = Color.Red
   Public Property NegativeColor() As Color
      Get
         Return _NegativeColor
      End Get
      Set(ByVal value As Color)
         _NegativeColor = value
      End Set
   End Property 'NegativeColor


   Private _ComparisionColumn As DataGridViewColumn
   Public Property ComparisionColumn() As DataGridViewColumn
      Get
         Return _ComparisionColumn
      End Get
      Set(ByVal value As DataGridViewColumn)
         _ComparisionColumn = value
      End Set
   End Property 'SourceColumn

   Private _UpdateInterval As Int32
   <System.ComponentModel.Description("Update time in seconds")> _
   Public Property UpdateInterval() As Int32
      Get …
TnTinMN 418 Practically a Master Poster

The only thing that I know of that causes the symptoms you have described is if the timestamp on you project files somehow becomes dated later than the curent datetime of your computer.

Exit VS an go to your project folder. Locate the "obj" and "bin" folders and delete them. Look at the date-modified on your ".vb" files. Make sure the datetimes on them is not greater than the current datetime of your computer. If it is, right-click on the file and select "open-with" NotePad or some other text editor. Add a blank line to the file and save it. This will change the timestamp to the current datetime. Then restart VS and open the project and try running by pressing the "F5" key. Then see if you can edit and the edits have effect.

TnTinMN 418 Practically a Master Poster

Are you running the capture on a secondary thread? Based on your class name, this looks like a high probability. If you are, your should not be directly accessing the UI controls from that thread. I suggest you follow a pattern similar to what is used below.

namespace ScreenCapture
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateImageDelegate = new RefreshPB(pictureBox1.Refresh);
            SetImage += new SetImageEventHandler(UpdateImage);
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        delegate void RefreshPB();

        private RefreshPB UpdateImageDelegate;

        private event SetImageEventHandler SetImage;
        private delegate void SetImageEventHandler(Image bmp);

        private void UpdateImage(Image bmp)
        {
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
            }

            pictureBox1.Image = bmp;
            if (pictureBox1.InvokeRequired)
            {
                pictureBox1.Invoke(UpdateImageDelegate);
            }
            else
            {
                pictureBox1.Refresh();
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            do
            {
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    break; // TODO: might not be correct. Was : Exit Do
                }
                if (SetImage != null)
                {
                    SetImage(ScreenShot.ScreenCapture.CaptureScreen());
                }
                System.Threading.Thread.Sleep(100);
            } while (true);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync(pictureBox1);
        }
    }
}

Replace my CatureScreen in this line: SetImage(ScreenShot.ScreenCapture.CaptureScreen()); with your code that returns a bitmap.