TnTinMN 418 Practically a Master Poster

Another give me code request from another I'm too lazy to search myself poster.

http://letmebingthatforyou.com/?q=gaussian%20filter%20vb6

hint it's on planetsource code

AndreRet commented: lol, very well said. ;) +13
TnTinMN 418 Practically a Master Poster

How is that any different than before? It still changes the combobox items on the Dropdown event. I assume that the list of students does not change during your program run, so fill the items array once in either the FormLoad or FormShown event handler.

Begginnerdev commented: Safer that way. +8
TnTinMN 418 Practically a Master Poster

Yes, of course. Embedding a file just merges a copy of it into the executable. The My.Resources provides it a Byte array. There are also tools that allow you to retreive it is as an IO.Stream.

Edit: Some programs may what to have the proper extension (.wmv, .jpg, etc.) and a temporary filename will have a ".tmp" extension. You can rename a file using System.IO.File.Move("oldpath\filename", "oldpath\newfilename") or you can use the VB helper method My.Computer.FileSystem.RenameFile.

TnTinMN 418 Practically a Master Poster

Ok. You now got it as an embedded resource, so for the player to play the movie, you will first have to write it to the disk. I like using temporary files for this.

Public Class Form1

    Dim tempfile As String = System.IO.Path.GetTempFileName

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       Dim strmTemp As IO.Stream = IO.File.Create(tempfile, 1024, IO.FileOptions.None)
       strmTemp.Write(My.Resources.back_blue, 0, My.Resources.back_blue.Length)
       strmTemp.Close()
       AxShockwaveFlash1.Movie = tempfile
    End Sub

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
       ' delete the temp file
       System.IO.File.Delete(tempfile)
    End Sub

End Class
TnTinMN 418 Practically a Master Poster

or any other solution if my way is too stupid

I would not say its stupid, just not well thought out. :)

Look at what you wrote as one of your goals: " Later in that form when user clicks on the panel stopwatch must start".

To accomplish this, you will be handling the panel's "Click" event. That has nothing to do with the name that you would assign to the Stopwatch ****if it had a Name property. ****

What you do need however is a reference to the StopWatch so that you can start and stop it. All Controls have a "Tag" Property, so you could assign the StopWatch to the Panel's Tag.

However this is just plain messy and hard to maintain. I suggest that you consider creating a UserControl instead. It would house it's own timer and Click logic. Then you would just add an instance of that instead of the panel to your form.

TnTinMN 418 Practically a Master Poster

An easy way to do this is to create a string collectionin My.Settings.

You can add/delete from it like any other list. Set it as the Listbox's DataSource.
ListBox1.DataSource = My.Settings.History

Just make sure that user settings is set to automatically save or do it in your code in the form closed event handler.

 Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
   My.Settings.Save()
End Sub

Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
My.Settings.Save()
End Sub

TnTinMN 418 Practically a Master Poster

I'm not going to claim that this is a better way, but it is one way that I find easy to read and work with.

      ' This method uses a CopmmandBuilder to build the commands

      ' You need to provide a DataApater with the select command defined
      ' for the command builder to work from.

      ' Since you are using all columns, a simple select * works

      Dim conn As New SqlConnection(My.Settings.NorthwindConnectionString)

      Dim adapter As New SqlDataAdapter()
      adapter.SelectCommand = New SqlCommand("Select * From Employees", conn)

      ' feed the adapter into the builder
      Dim cmdbuilder As New SqlCommandBuilder(adapter)

      ' get the insert command. Tell it to use column names for paramters
      Dim inscmd As SqlCommand = cmdbuilder.GetInsertCommand(useColumnsForParameterNames:=True)
      ' now just fill the parameters
      ' the name format is: @ColumnName
      ' in the column name has a space(" ") in it, it is replaced with "_"

      With inscmd
         .Parameters("@Last_Name").Value = "Jones"
         .Parameters("@First_Name").Value = "William"
         .Parameters("@Title").Value = "CCABW"
         .Parameters("@TitleofCourtesy").Value = "Mr."
         .Parameters("@BirthDate").Value = #1/1/1955#
         .Parameters("@HireDate").Value = #6/23/1978#
         .Parameters("@Address").Value = "Somewhere"
         .Parameters("@City").Value = "MyTown"
         .Parameters("@Region").Value = "All"
         .Parameters("@PostalCode").Value = "24312"
         .Parameters("@Country").Value = "USA"
         .Parameters("@HomePhone").Value = "1234332345"
         .Parameters("@Extension").Value = ""
         .Parameters("@Photo").Value = DBNull.Value
         .Parameters("@Notes").Value = ""
         .Parameters("@ReportsTo").Value = 4
         .Parameters("@PhotoPath").Value = ""
      End With

      conn.Open()
      inscmd.ExecuteNonQuery()
      conn.Close()
Reverend Jim commented: Another neat trick. +0
TnTinMN 418 Practically a Master Poster

I wish you the best of luck with this.

If MS does finally see the light and provide an update, I hope that they also will have the sense to draw the line on the .Net side of things and admit that it is not a natural progression from VB6 and in doing so eliminate the stuff in it that tries to tie it back to VB6. That stuff only confuses people.

AndreRet commented: my thoughts exactly. :) +13
TnTinMN 418 Practically a Master Poster

I am beginning to suspect that the issue is the MDI taskbar that shows up when you maximize a child form. I have attached a simple project for you to play with.

MDI1

Begginnerdev commented: That was nice of you. +8
TnTinMN 418 Practically a Master Poster

I just had another thought, try moving your maximize code from the Load handler to the Shown handler.

TnTinMN 418 Practically a Master Poster

Random is a pseudoRandom generator. You are creating a new instance each time. Without checking the docs, I believe it seeds based on system time. Therefore your seed value on differs only a bit on each creation.

Try this:

Private rnd As New Random
Private Sub Me_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown

   DrawColor(New Rectangle(50, 50, 100, 100))
    For i As Int32 = 0 To 20
        DrawColor(GimmiRectangle)
    Next
End Sub

Private Sub DrawColor(ByVal rNew As Rectangle)
    Try
        Dim g As Graphics = Me.CreateGraphics

        g.DrawRectangle(New Pen(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))), rNew)
        g.Dispose()

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Private Function GimmiRectangle() As Rectangle
    Try
        Dim rect As New Rectangle(rnd.Next(1000), rnd.Next(1000), rnd.Next(1000), rnd.Next(1000))
        Return rect
    Catch ex As Exception
        MsgBox(ex.ToString)
        Return New Rectangle(0, 0, 0, 0)
    End Try
End Function
TnTinMN 418 Practically a Master Poster

Update the underlying datatable directly. This will ensure that the changes are reflected in the dataview.

Something like this:

Public Class Form1

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

      Dim r As DataRow
      With dtSource
         .Columns.Add("store", GetType(String))
         .Columns.Add("hours", GetType(Double))
         r = .NewRow : r(0) = "s1" : r(1) = 3.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s1" : r(1) = 5.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s1" : r(1) = 51.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s1" : r(1) = 13.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s1" : r(1) = 33.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s2" : r(1) = 35.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s2" : r(1) = 54.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s2" : r(1) = 23.0# : .Rows.Add(r)
         r = .NewRow : r(0) = "s2" : r(1) = 31.0# : .Rows.Add(r)
         .DefaultView.Sort = "[hours] Asc"
      End With
      DataGridView1.DataSource = dtSource.DefaultView
   End Sub


   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      AddhoursToStore("s1", 50.0#)
   End Sub

   Sub AddhoursToStore(ByVal store As String, ByVal hrsToAdd As Double)
      For Each row As DataRow In dtSource.Select("[store] = '" & store & "'")
         row("hours") = CType(row("hours"), Double) + hrsToAdd
      Next
   End Sub
End Class
TnTinMN 418 Practically a Master Poster

I've also done something with tab controls before and hooking into the draw at run time to hide the actual tabs showing, then programatically hopping between the two

This works well if you want to keep all the controls and their handlers under one form.

The method I use is to set the DrawMode to OwnerDrawn fixed, Appearance to "Buttons" and the ItemSize to (5,5).

This allows you to click on the the buttons to change Tabs while in the designer and does not take away much design space.

The wrinkle that I throw in is to place a docked panel as the first control on each tab. Then all other controls are parented to that panel.

The tabcontrol is parented in a panel on the form during design. I set tabcontrol's Parent property to null on loading the form. This leaves it fully functional just hidden and out of the way.

I then play a Parent swap game with each TabPage's first control (the panel mentioned above) by setting it's Parent property to the panel that originally parented the tabcontrol. I use the SelectedTab property to keep track of whick panel is currently parented to the form.

Mike Askew commented: Another good implementation +6
TnTinMN 418 Practically a Master Poster

What did you not understand about the information that I provided you? You still have the issues no matter which method you use to convert the byte array to an image. If the the byte array is null, it will fail.

Begginnerdev commented: Some people will never learn. +8
TnTinMN 418 Practically a Master Poster

@Andre, did you by chance mean to use InstrRev in line 6 of your code?

Here's my entry for this mundane function.

Function RemoveExt(fname As String, Optional extToRemove As String = "") As String
    ' if extToRemove = "" then all extensions removed
    Dim pt_pos As Integer
    pt_pos = InStrRev(fname, ".")
    If pt_pos <> 0 Then
        If extToRemove = "" Then
            'Remove all extensions
            RemoveExt = Left(fname, pt_pos - 1)
        Else
            extpart = Right(fname, (Len(fname) - pt_pos) + 1)
            If LCase(extpart) = LCase(extToRemove) Then
                RemoveExt = Left(fname, pt_pos - 1)
            Else
                RemoveExt = fname
            End If
        End If
    Else
        RemoveExt = fname
    End If
End Function
AndreRet commented: Indded, because of more functionality :) +13
TnTinMN 418 Practically a Master Poster

I'm not sure this what you are attempting, but I have assumed:

  1. you need to read an xml source file
  2. you need to add a new "students" element
  3. you want to save the file with "students" sorted on "Day"

      Dim doc As New Xml.XmlDocument ' create a XMLDocument to hold the file
      doc.Load("SourceFile.xml")     ' load the file
    
      ' Since Events is your main element it is the "DocumentElement"
      Dim Events As Xml.XmlNode = doc.DocumentElement
    
      ' add a new "students" element to "Events"
         Dim elStudents As Xml.XmlElement = doc.CreateElement("students")
         Dim elDay As Xml.XmlElement = doc.CreateElement("Day")
         elDay.InnerText = "3"
         elStudents.AppendChild(elDay)
         Events.AppendChild(elStudents)
    
      ' since there are only "students" elements as child nodes of "Events", 
      ' all child nodes are "students"
    
      ' we will create a list that can be sorted and load it from "Events.ChildNodes"
    
      Dim sortedstudents As List(Of Xml.XmlElement) = _
         (From el In Events.ChildNodes Select CType(el, Xml.XmlElement)).ToList
    
      ' I am assuming that "Day" is an Integer;
      ' therefore, I am converting it to an Integer for comparison during sorting
    
      sortedstudents.Sort(Function(el1 As Xml.XmlElement, el2 As Xml.XmlElement) _
                           CInt(el1.SelectSingleNode("Day").InnerText).CompareTo( _
                           CInt(el2.SelectSingleNode("Day").InnerText)))
    
      Events.RemoveAll() ' Delete all exiting child nodes from Events
    
      ' now append the sorted "students" elements to the empty "Events" element
    
      For Each el As Xml.XmlElement In sortedstudents
         Events.AppendChild(el)
      Next
    
      ' save the processed file
      doc.Save("fred.xml")
    
TnTinMN 418 Practically a Master Poster

Just a bit of info to add to the discussion.

Your original code will give you your expected result if you change
objWriter.Write(editor.RichTextBox1.Text)
to
objWriter.Write(editor.RichTextBox1.Rtf)

Those dang computers always try to do what you tell them to do, not what you want them to do. :)

That said, its easier to use the Save and Load methods as Jim has shown you.

DyO152 commented: Thanks. +0
TnTinMN 418 Practically a Master Poster

Is the DGV bound to a datatable?
Can you except the DGV showing only rows that match your search criteria?
If so, consider using setting the row filter on the datatable's DefaultView or creating a DataView and using it as the DGV's datasource.

Begginnerdev commented: Very true +7
TnTinMN 418 Practically a Master Poster

I guess if you you have it formatted to a short date format, then allowing the user to invoke the dropdown to show the MonthCalndar may be of some use.

Anyways, making a readonly DTP control is fairly easy.

Public Class ReadOnlyDTP
   Inherits DateTimePicker
   Public Shadows Property Value() As DateTime
      Get
         Return MyBase.Value
      End Get
      Set(ByVal value As DateTime)
         ' Need to set values in correct order 
         ' to prevent internal validation error
         Select Case value
            Case Is < MyBase.Value
               MyBase.MinDate = value
               MyBase.Value = value
               MyBase.MaxDate = value
            Case Is > MyBase.Value
               MyBase.MaxDate = value
               MyBase.Value = value
               MyBase.MinDate = value
         End Select
      End Set
   End Property 'Value

   Const WM_Char As Int32 = &H102
   Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
      ' prevent keyboard changes to the fields
      If m.Msg = WM_Char Then Exit Sub
      MyBase.WndProc(m)
   End Sub
End Class

Add this to your project, build the project and it should showup in your ToolBox if your VS is configured to do so (it is the default setting).

Reverend Jim commented: I've been wanting just that trick for something else. Thanks. +12
TnTinMN 418 Practically a Master Poster

Jim has a minor error in his code:

 "SELECT * FROM invoiced_filter " & _
" WHERE (Invoiced > #" & fromdte & "# AND Invoiced < #" & todte & "#)"

Access also supports the Between statement but it requires the hash mark ("#") as Jim shown.

 "SELECT * FROM invoiced_filter " & _
" WHERE (Invoiced Between #" & fromdte & "# AND Invoiced < #" & todte & "#)"
Reverend Jim commented: That's why I like to test these things before posting ;-P +12
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

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

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
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

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

that's what I get from free handing it; complaints about 2 transposed leters that you then turn into a whole different method. :-/

If dp.YValues(0) > DateTime.FromOADate(Chart1.ChartAreas("Fred").AxisY.Minimum).Add(New TimeSpan(0, 3, 0)).ToOADate Then

TnTinMN 418 Practically a Master Poster

Perhaps a quick refresher read will help you gel your thought process. It has pretty pictures (I like pictures). :)

http://www.c-sharpcorner.com/UploadFile/eecabral/OOPSand.NET211102005075520AM/OOPSand.NET2.aspx

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

I am posting this in response to those who ask about replacing the webbrowser (WB) control’s default browser. You cannot ask the WB control to use a different browser, it is hardwired to use the current version of Microsoft’s Internet Explorer that is installed on the target computer.

It may appear that the WB control is using an older version than is installed; this is not the case. Microsoft in their infinite wisdom made the decision to make IE 7 the default-rendering mode for all applications that use the WB control. This can be observed by visiting this website:

http://detectmybrowser.com

This can be overridden by adding the application name to the registry key:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Doing this can be a royal pain in the butt. Especially when developing a program as you would need to make one entry for “ApplicationName.exe” and one for “ApplicationName.vshost.exe” (for debugging under VS).

This code adds and deletes the registry entry on the fly for you. Just add it to your project. That is all that needs to be done. It automatically makes the registry changes for you.

Disclaimer: This code makes changes to the registry on Windows based systems. This is an inherently dangerous operation. The author assumes no responsibity for issues related to your use of this code. Use at your own risk.

john.knapp commented: bookmarked! +3
TnTinMN 418 Practically a Master Poster

I'm getting old and sloppy in my coding; it is a datatype precision mistake.

change
Dim targetY As Single = CSng(area.AxisY.Minimum + ((targetTS.Ticks / deltaTSticks) * (area.AxisY.Maximum - area.AxisY.Minimum)))

to

Dim targetY As Double = (area.AxisY.Minimum + ((targetTS.Ticks / deltaTSticks) * (area.AxisY.Maximum - area.AxisY.Minimum)))

TnTinMN 418 Practically a Master Poster

What is the error message?
Linq is not the fastest in the world. How many data points do you have (approximately)?

For drawing the line, you need to scale the position to the axis as the labels are not the axis values. We had to fake it into using the timespan values with the custom labels.

     Private Sub Chart1_PostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataVisualization.Charting.ChartPaintEventArgs) Handles Chart1.PostPaint
          If TypeOf e.ChartElement Is ChartArea Then

              Dim area As ChartArea = CType(e.ChartElement, ChartArea)

              Dim x1 As Single = CSng(area.AxisX.ValueToPixelPosition(area.AxisX.Minimum))
              Dim x2 As Single = CSng(area.AxisX.ValueToPixelPosition(area.AxisX.Maximum))

              ' need to scale the targetY value to the y-Axis values

              Dim targetTS As New TimeSpan(0, 3, 0) 'your 00:03:00

              ' when we originally setup the Y-Axis we used OADates to create a numeric value
              ' now convert these back to .Net datetime and get the range in Ticks
              Dim deltaTSticks As Int64 = DateTime.FromOADate(area.AxisY.Maximum).Ticks - DateTime.FromOADate(area.AxisY.Minimum).Ticks

              ' It is a linear scale:  y = y(0) + slope * X
              ' where X is targetTS.tick
              '       slope = (area.AxisY.Maximum - area.AxisY.Minimum) / deltaTsticks
              '       y(0) = area.AxisY.Minimum 
              '       y = targetY
              Dim targetY As Single = CSng(area.AxisY.Minimum + ((targetTS.Ticks / deltaTSticks) * (area.AxisY.Maximum - area.AxisY.Minimum)))

              ' now convert to pixel position
              Dim y As Single = CSng(area.AxisY.ValueToPixelPosition(targetY))

              e.ChartGraphics.Graphics.DrawLine(New Pen(Color.Blue, Width:=5), x1, y, x2, y)

          End If
     End Sub
TnTinMN 418 Practically a Master Poster

So this crashing as soon as you start the application?

Can you post all MnForm.vb so that we can see the offending line 13?

The snippett you posted should be fine, so I can only make guesses at this point and ask that you try rebooting your machine and then run the app without VS started. There have been some report memory leak issues with WMI, but I don't see anything at this point that would trigger those.

Also what version of VS are you running and what version of the framework are you targeting? These are probably not an issue, but more info is always better.

Is this a release or debug build?

TnTinMN 418 Practically a Master Poster

Aah, the old who has focus when I get clicked dilemma.

If there is no reason that the button needs to be focused, then you can create a nonselectable button or any other control for that matter. The only drawback of this technique is that the button can not be access via the keyboard (Tab, Enter).

  Public Class NoFocusButton
     Inherits System.Windows.Forms.Button
     Public Sub New()
        SetStyle(ControlStyles.Selectable, False)
     End Sub
  End Class

Just add this to your project and perform a build operation. It should show up at the top of your toolbox.

This is a useful alternative to a toolstrip button.

Reverend Jim commented: Cleaner and easier. Thanks. +12
TnTinMN 418 Practically a Master Poster

how will i change that connection/datasource as what the user wants?

I thought you did not want them to be able to change the DataSource.

If you need to allow them to select a server, maybe this will work for you?

    Dim csb As New SqlClient.SqlConnectionStringBuilder

    csb.IntegratedSecurity = True
    csb.UserInstance = True

    ' Full File Path Works with both these DataSource constructs
    'csb.AttachDBFilename = "F:\SQLServer2008\AttachedDBTest.mdf"
        ' DataSource = ".\" & InstanceName
        ' DataSource = ServerName & "\" & InstanceName


    ' |DataDirectory| only works with DataSource = ".\" & InstanceName
    csb.AttachDBFilename = "|DataDirectory|\AttachedDBTest.mdf"

    ' Try to retrieve the available servers
    Dim dtSQLServers As DataTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources()
    If dtSQLServers.Rows.Count > 0 Then
        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 = ".\" & InstanceName
            'csb.DataSource = ServerName & "\" & InstanceName

        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

    End If

    Dim conn As New SqlClient.SqlConnection(csb.ConnectionString)

    conn.Open()
    conn.Close()
john.knapp commented: <snippet>nice!</snippet> +3
TnTinMN 418 Practically a Master Poster

Well here's one las t update. I added a few for comments to help you uderstand whats in there and cleaned up the code.

As far as things to help you learn.

  1. First and of high important. Set Option Strict On, Option Explicit Off, and Option Infer Off as defaults in your settings. You may hate that you have to do some extra typing, but it will save you much more time in debugging. It will also make you think about why VS is now saying that you should not do some code in a certain way.

  2. Your search engine is your friend. If you are looking for help on a certain keyword or method, try searching for "msdn what you are looking for". This used to mainly take you directly to the documentation page, but I noticed that lately, it pulls more from the microsoft forums. Both can be useful and bad at the same time. If you are looking at the documentation, scroll to the end of the page; that is where the community feedback is and there is often corrections and sometime sample code placed there.

  3. Let VS help you zero in on possible things to investigate further. Right click on methods and click "Go to definition" This helps see more information about the method and can help think about what to go looking for.

  4. Sample code is always good, but you will most likely for the source code as C#. This is OK, because in reality …

Reverend Jim commented: Good advice +12
TnTinMN 418 Practically a Master Poster

Can you take a look on the code again?

Good thing I did. Found some serious logic errors. Good example of that just because it worked, doesn't mean its right.

Now has color setting capabilty and rounded corners. Yes, I had to tweak it. ;)
I really want to use a pointed crystal shape, but writing a custom shape is will take some time. I also add some stuff to make it nicer to use a control. Feel free to ask if you have questions.

Please close this thread if your happy with it.

TnTinMN 418 Practically a Master Poster

First off, COOL project.

I think what you want is to define this as a user control so that you can place multiple instances on a form. I apolgize for totally rewriting your code, but it looked like to much fun to play with for me not to turn it into a control I will use.

Here is the modified project. I did not impliment your track bar, but I think you can deal with that.

Edit: I forgot to mention, just rebuild the project. The Digit control should showup on your toolbar.

Reverend Jim commented: Excellent post. +12
TnTinMN 418 Practically a Master Poster

Hi Lulu,

You are sure beating that example code to death! :-)

You should really post more of the code when you are asking for help. People are not going to know what DTRow is for example.

Oh well, so much fo my pedantic streak. Here is one way you could do it.

      Dim group As IEnumerable(Of DataRow) = _
         From sortrow As DataRow In ( _
         From row In DS.Tables(0).AsEnumerable() _
         Group row By LINENAME = row.Field(Of String)("LINENAME") Into grp = Group _
         Order By LINENAME _
         Select DTRow(grpDT, _
                      New Object() {LINENAME, _
                                    myToday.Add( _
                                                New TimeSpan(CType( _
                                                                     grp.Average(Function(r2 As DataRow) TimeSpan.Parse(r2.Field(Of String)("EVENTTM")).Ticks),  _
                                                                     Int64 _
                                                                   ) _
                                                            ) _
                                               ) _
                                   } _
                     ) _
         ) Order By sortrow.Item("EVENTTM")

Or you could just do it on your datatable.

      'Add the query results to the new Table
      For Each row As DataRow In group
         grpDT.Rows.Add(row)
      Next

      grpDT.DefaultView.Sort = "[EVENTTM] Asc" ' for ascending


      'grpDT.DefaultView.Sort = "[EVENTTM] Desc" ' for descending 


      'Assign new Table as DataSource of DGV
      GridView1.DataSource = grpDT.DefaultView

Select one way or the other. Not Both.

TnTinMN 418 Practically a Master Poster

Did some playing around and found putting the search into a separate function increased the speed by a factor of approximately 4(i.e. on my machine original code was 1200-1300, the new code
300-400)
You also switched to using a char for the seek parameter versus char which is the the reason for the speed increase not the fact that it hidden under another function.

If the OP would change: str.IndexOf(",", 0) to str.IndexOf(',', 0) the factor of 4 performance boost would also be observed.

So there is a lesson in this; when seeking for one char use the char overload not the string overload.

TnTinMN 418 Practically a Master Poster

i took a form and dragged and dropped that database as details view. first i arranged labels in row format and their respective text boxes under them. and i made copies of text boxes of first row text by holding Ctrl key

The details view is just that the details for a single record. The origianl textboxes created by the drang 'n drop are bound to the naviagtor that should also have been create by that operation. The textboxes will show the details for the currently selected record indicated in the naviagor position box. Even if you correct the binding definition that got lost when copying. Each row would show the same data.

To have multiple rows of details, you would need to have multiple binding navigator (or some other binding method) set up for the additional rows a where each sucessive row would be incremented one greater thean the row above. But what happens if your retrieved data has less than four rows like shown in the picture. If this case you would have to have code to remove the binding and blank out the empty rows. Yes it can be done, but it will involve a fair amount of coding to achieve.

If you want multiple rows, use a datagridview.

TnTinMN 418 Practically a Master Poster

Jim's method is probably the simplest and qickest in performance terms, but I would recommend that the linked textbox be passed to the second form versus hard coding the reference. The TB could be passed in the form's contructor, be a property on the form or passed in the Show or ShowDialog method.

Since you asked about databinding, I'll show that method and pass the TB in Show method. Binding should be removed when not needed, so that is done in the FormClosed event handler.

Public Class Form2

  Public Shadows Sub Show(ByVal tb As TextBox)
     SetLinkedTB(tb)
     MyBase.Show()
  End Sub

  Public Shadows Sub ShowDialog(ByVal tb As TextBox)
     SetLinkedTB(tb)
     MyBase.ShowDialog()
  End Sub

  Private LinkedTB As TextBox
  Private LinkedTBBinding As Binding
  Private Sub SetLinkedTB(ByVal tb As TextBox)
     TextBox1.Text = tb.Text
     TextBox1.SelectionStart = tb.SelectionStart
     TextBox1.SelectionLength = tb.SelectionLength
     LinkedTBBinding = New Binding("Text", TextBox1, "Text", False, DataSourceUpdateMode.OnPropertyChanged)
     tb.DataBindings.Add(LinkedTBBinding)
     LinkedTB = tb
  End Sub

  Private Sub Form2_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
     LinkedTB.DataBindings.Remove(LinkedTBBinding)
     LinkedTB.SelectionStart = TextBox1.SelectionStart
     LinkedTB.SelectionLength = TextBox1.SelectionLength
  End Sub
End Class

usage:

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     Form2.Show(TextBox1)
  End Sub
john.knapp commented: nice code! I've been beating myself up with databinding the last few days - fixing an MS walkthrough and all :) +0
TnTinMN 418 Practically a Master Poster

That's what I figured. If you open the file with Notepad, you will probably see that it contains Html code. Two possible causes of this are that the adress you have is not the true download link or that site requires cookies to authenticate the download.

I have not found a solution to the first one. All that can be done is capture the Navigating event and print out the "e.url" property in the event and look through the results. There will probably be several Urls printed out,

If you do have that right link but need to supply cookies, I created an extended WebClient class to retrieve the cookies.

Imports System.Runtime.InteropServices

Public Class WebClientwithCookies
   Inherits Net.WebClient

  Private mycookies As New Net.CookieContainer()
   Public Shadows Sub DownloadFile(ByVal url As String, ByVal filename As String)
      mycookies.SetCookies(New Uri(url), GetCookies(url))
      MyBase.DownloadFile(url, filename)
   End Sub

   Public Shadows Sub DownloadFile(ByVal url As Uri, ByVal filename As String)
      mycookies.SetCookies(url, GetCookies(url.ToString))
      MyBase.DownloadFile(url, filename)
   End Sub


  Protected Overrides Function GetWebRequest(ByVal address As Uri) As Net.WebRequest

   Dim request As Net.WebRequest = MyBase.GetWebRequest(address)

   If request.GetType() Is GetType(Net.HttpWebRequest) Then
   CType(request, Net.HttpWebRequest).CookieContainer = mycookies
   End If

   Return request

  End Function

   Public Enum CookieError
      ERROR_NO_MORE_ITEMS = 259
      ERROR_INSUFFICIENT_BUFFER = 122
      ERROR_INVALID_PARAMETER = 87
   End Enum

   <DllImport("wininet.dll", SetLastError:=True)> _
   Public Shared Function InternetGetCookie(ByVal url As String, _
                                            ByVal cookieName As String, _
                                            ByVal cookieData As System.Text.StringBuilder, _
                                            ByRef size As Int32) As Boolean
   End Function

   Public Shared Function GetCookies(ByVal uri As String) As String
      Dim datasize As Int32 = 1024
      Dim cookieData As New …
TnTinMN 418 Practically a Master Poster

This does not answer the question you posted, but it does what you said you wanted to accomplish; kill the java process currently running under the browser control.

Imports System.Runtime.InteropServices

Public Class Form1

   Private Sub btnKillJava_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnKillJava.Click
      KillJavaForBrowser(WebBrowser1)
   End Sub

   Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
      BrowserRefresh(WebBrowser1)
   End Sub

   Private Sub KillJavaForBrowser(ByVal browser As WebBrowser)
      ' get a list of the browser's child windows
      Dim childHandles As List(Of IntPtr) = NativeMethods.GetChildWindows(browser.Handle)

      ' make a list of PID's associated with these child window handles

      Dim childPIDs As New List(Of IntPtr)
      Dim pid As IntPtr

      For Each h As IntPtr In childHandles
         pid = IntPtr.Zero
         NativeMethods.GetWindowThreadProcessId(h, pid)
         childPIDs.Add(pid)
      Next h

      ' loop through the unique child window PID's searching for java.exe

      For Each pid In childPIDs.Select(Function(id As IntPtr) id).Distinct.ToList
         Dim p As Process = Process.GetProcessById(pid.ToInt32)
         If p.MainModule.ModuleName.ToLower = "java.exe" Then
            ' found it, so kill it and stop loop
            p.Kill()
            Exit For
         End If
      Next pid
   End Sub

   Private Sub BrowserRefresh(ByVal browser As WebBrowser)
      browser.Navigate(browser.Url)
   End Sub
End Class


Public Class NativeMethods
   <DllImport("User32.dll")> _
   Private Shared Function EnumChildWindows _
     (ByVal WindowHandle As IntPtr, ByVal Callback As EnumWindowProcess, _
     ByVal lParam As IntPtr) As Boolean
   End Function

   Public Delegate Function EnumWindowProcess(ByVal Handle As IntPtr, ByVal Parameter As IntPtr) As Boolean

   Public Shared Function GetChildWindows(ByVal ParentHandle As IntPtr) As List(Of IntPtr)
      Dim ChildrenList As New List(Of IntPtr)
      Dim ListHandle As GCHandle = GCHandle.Alloc(ChildrenList)
      Try
         EnumChildWindows(ParentHandle, AddressOf EnumWindow, GCHandle.ToIntPtr(ListHandle))
      Finally …
renzlo commented: thanks +2
TnTinMN 418 Practically a Master Poster

I'm sure your professors would find this to be an interesting topic:

"How I am earning a degree in computer programming without ever having to learn the material via the use of internet help forums"

Reverend Jim commented: Sounds like a real winner +12
TnTinMN 418 Practically a Master Poster

I suspect your problem is that the splitcontainer only captures the mouse when you move over the splitterbar. Try wiring up the mouse move event for each panel in the container like this:

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     AddHandler SplitContainer1.Panel1.MouseMove, AddressOf SplitContainer1_MouseMove
     AddHandler SplitContainer1.Panel2.MouseMove, AddressOf SplitContainer1_MouseMove
  End Sub

  Private Sub SplitContainer1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles SplitContainer1.MouseMove
     Debug.WriteLine(MousePosition.ToString)
  End Sub
TnTinMN 418 Practically a Master Poster

Assuming that you are using VB's "application framework" you have a couple of options. To ensure that the framework is enabled, go to the "Solution Explorer" and either double-left click on "My Project" or right-click on it and select open.
Open_Props

This will open the project's property setting page.

props_page

Make sure that the "Enable application framework is checked". No notice the "Shutdown mode" combobox. In this case it is set to "When startup form closes". This means exactly as is implied, the application shutsdown when the startup form is closed.

Now assuming that you are using the "Application.Exit" method (not the "End" statement) to exit the application either via clicking your close program button or in the "FormClosing" event handler, you can put your logout code in just the "Startup Form's closing event handler. No need to put this logic in all of the forms. By using "Application.Exit" versus "End", you allow all message loops to complete first. The "End" statement does very little cleanup and like slamming the door closed on the application.

Another option would be to using the application's "Shutdown" event handler. You access the code page for this event by clicking on the "View Application Events" button shown in the above picture.

app_events_1

shutdown_event

coded_shutdown
Now you add you logout code under the shutdown event. The "My" namespace is meant to be your extentable …

Reverend Jim commented: Excellent advice +12
john.knapp commented: excellent, should be a tutorial +3
TnTinMN 418 Practically a Master Poster

Add a property to "infoEntry" to accept a reference to the ListView.

    private ListView _lv;
    public ListView lv
    {
        get { return _lv; }
        set { _lv = value; }
    }

Then set that property before showing "dataWindow"

dataWindow.lv = this.toSend;
dataWindow.ShowDialog();

Then: lv.Items.Add("test").SubItems.AddRange(row1);

TnTinMN 418 Practically a Master Poster