TnTinMN 418 Practically a Master Poster

As a matter of interest, do you know if there is a way to do a similar query on a dataset using LINQ?

You would have to run Linq against the DataTable.Rows collection. You could also use the DataTable.Compute method for a non-Linq solution.

   Dim dt As New DataTable
   Dim r As DataRow
   'make some data to work with
   With dt
      .TableName = "fred"
      .Columns.Add(New DataColumn("Account", GetType(Int32)))
      .Columns.Add(New DataColumn("master code", GetType(String)))
      .Columns.Add(New DataColumn("score", GetType(Int32)))
      r = .NewRow : r(0) = 100 : r(1) = "code1" : r(2) = 1 : .Rows.Add(r)
      r = .NewRow : r(0) = 101 : r(1) = "code1" : r(2) = 1 : .Rows.Add(r)
      r = .NewRow : r(0) = 103 : r(1) = "code1" : r(2) = 1 : .Rows.Add(r)
      r = .NewRow : r(0) = 105 : r(1) = "code3" : r(2) = 1 : .Rows.Add(r)
      r = .NewRow : r(0) = 300 : r(1) = "code3" : r(2) = 32 : .Rows.Add(r)
      .AcceptChanges()
   End With
   'Put it in a dataset, since that was what was asked for
   Dim ds As New DataSet
   ds.Tables.Add(dt)

   Dim searchcode As String = "code3" 'something to seek

   'Option 1: DatatTable.Compute method
   Dim total1 As Int32 = CType(ds.Tables("fred").Compute("Sum([score])", "[master code]='" & searchcode & "'"), Int32)

   'Option 2: Use Linq Extensions
   'Note:  I despise Anonymous Types and Inference, so I use typed Linq
   Dim scores As IEnumerable(Of Int32) = From row In ds.Tables("fred").Rows Where CType(CType(row, DataRow).Item("master code"), String) = searchcode Select CType(CType(row, DataRow).Item("score"), Int32)
   Dim total2 …
TnTinMN 418 Practically a Master Poster

I am attaching the VS2008 Solution, so you don't need to worry about copying all this stuff.

Ok,
Since you stated you did not want a database, I recommend using a user setting variable of type DataTable.

UserSettingDT2

With this you can do all the same stuff you can do if you where to retrieve the values from say a SQL Server database. It just eliminates that step and we make the built-in usersettings stuff do the saving and retrieval of the data.

We need to still define a data structure, but that is pretty easy. Substitute and add your textboxes for the 3 default ones I used. You can add this as a seperate class in VS or get paste it after the Form1 code.

Public Class StoredRecordsDT
    Inherits System.Data.DataTable
    Public Sub New()
        With Me.Columns
            .Add(New DataColumn("TextBox1", GetType(String)))
            .Add(New DataColumn("TextBox2", GetType(String)))
            .Add(New DataColumn("TextBox3", GetType(String)))
        End With
    End Sub
End Class

The code for Form1 (with the datagridview and bindingnavigator)". The bindingnavigator is just a toolstrip that keeps things looking consistant with other database applications,

'For info on location of the user.config file see: http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
Public Class Form1
   Private RecordsBindingSource As New BindingSource

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      If My.Settings.Records Is Nothing Then
         'Table has not yet been stored, or has been set to Nothing
         My.Settings.Records = New StoredRecordsDT
         My.Settings.Records.TableName = "Records"
      End If

      'set bindingsource datasource to use the user settings datatable …
TnTinMN 418 Practically a Master Poster

Sean,

Before I even attempt to offer advice on this I want to make sure we have the goals well defined.

So here is how I have distilled your description.

Form1 contains: datagridview

Form2 contains: multiple textboxes and a "Send Button"

On clicking "Send", the contents of the textboxes are to be saved and used as the source data to define a row in the datagridview. You want the capability to repopulate the textboxes on Form2 by doubleclicking on a populated row of the datagridview on Form1. You did not ask for this, but I assume that you also want the ability to add new records and delete old ones?

Does this accurately describe what you want to accomplish? If not, please elaborate any needed changes.

TnTinMN 418 Practically a Master Poster

Assuming that the datagridview is bound to a datatable, then you can use the DataTable.Compute method.

Dim total As Decimal = CDec(dt.Compute("Sum([Payments])", "True"))

Where "dt" is the name of the datatable. I assumed that the column name in the datatable for "paymenents" is "Paymenents".

M.Waqas Aslam commented: very nice one , i dont know about it before . +0
TnTinMN 418 Practically a Master Poster

want to make a little request or question, is it possible to re-encrypt the encrypted file ? example its encrypted is it able to convert the encryption to binary (0100001001101001011011100110000101110010011110010010000001000011011011110110010001100101), and be able to read it and then decrypt and then load it to the accounts ? because the binary will be only 1 lin not multiple. Thx :)

Unless you have a program that reads one byte at a time and converts it to a string representation of eight bits that comprise each byte, you will never see "10101111.....".
All files are stored in binary. Howver, there is this thing called encoding that defines how the bytes and their values are to be interpreted. To convert each bit to a 1 or 0 and store that string so that you could view it in say Notpad) would be extremely inefficient as each bit of the original will now occupy eight bits in the stored.

If you want only one line to appear in the editor when you open the data file, then this modification will produce that.

    Private Sub WriteAccounts(ByVal filename As String, ByVal Accounts As List(Of Account))
      Dim Security As New Security

      'create file on each save
      Dim fs As IO.FileStream = IO.File.Open(filename, IO.FileMode.Create, IO.FileAccess.Write)
      Dim bw As New IO.BinaryWriter(fs)
      'write a binary Account to the file
      For Each acct As Account In Accounts
         bw.Write(Security.encryptString(acct.ToString))
      Next
      bw.Close()
    End Sub

   Private Sub ReadAccounts(ByVal filename As String, ByVal Accounts As List(Of Account))
      Dim Security As …
TnTinMN 418 Practically a Master Poster

Put the controls you are enabling/disabling in a container control (panel or group) if possible. Then just enable or disable that one. The child controls will be enabled/disabled as well.

iFrolox commented: Yea, its what i had to do. +1
TnTinMN 418 Practically a Master Poster

Assuming this is the code that you are using to write the file (found in your other thread),

Private Sub WriteAccounts(filename As String, Accounts As List(Of Account))
    Dim lines As String = ""
    For Each acct As Account In Accounts
        lines &= acct.ToString() & vbCrLf
    Next
    System.IO.File.WriteAllText(filename, lines)
End Sub

you could modify it something like this

    Private Sub WriteAccounts(ByVal filename As String, ByVal Accounts As List(Of account))
        Dim encrypt As New Security
        Dim sb As New System.Text.StringBuilder(500)
        For Each acct As account In Accounts
            sb.AppendLine(encrypt.encryptstring(acct.ToString))
        Next
        System.IO.File.WriteAllText(filename, sb.ToString)
    End Sub

    Private Sub ReadAccounts(ByVal filename As String, ByVal Accounts As List(Of account))
        Dim encrypt As New Security
        Accounts.Clear()
        Dim lines() As String = System.IO.File.ReadAllLines(filename)
        Dim decrypted As String
        For Each ln As String In lines
         decrypted = encrypt.decryptstring(ln)
         Accounts.Add(New account(decrypted.Split(","c)))
        Next
    End Sub
iFrolox commented: Went ahead of me and did it for me XD thanks for saving my time :) worked perfectly +1
TnTinMN 418 Practically a Master Poster

If you are not limiting the allowable characters in the textbox to exclude characters that the "LIKE" statement uses, you should preprocess the textbox's text to bracket those characters similar to like what I have shown in my example. I believe the SQL "LIKE" command treats these as special characters: "[", "]", "%", and "_".

I would suggest that you do not query the database for each change to the textbox. Just fill the underlying datatable with all the records and use a dataview as the datasource for the datagridview. You change the dataview's rowfilter based on the textbox. This example is just to demo the filter logic and does not require a database to fill the table. So just ignore the filling of the datatable part of it. It is the dataview logic that is important.

Public Class Form1
   Private dt As New DataTable("fred")
   Private filter As New DataView(dt)
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

      Dim r As DataRow
      With dt
         .Columns.Add(New DataColumn("name", GetType(String)))
         r = .NewRow : r(0) = "dan" : .Rows.Add(r)
         r = .NewRow : r(0) = "danny" : .Rows.Add(r)
         r = .NewRow : r(0) = "fred" : .Rows.Add(r)
         r = .NewRow : r(0) = "andrew" : .Rows.Add(r)
         r = .NewRow : r(0) = "mary" : .Rows.Add(r)
         r = .NewRow : r(0) = "sue" : .Rows.Add(r)
         r = .NewRow : r(0) = "jill" : .Rows.Add(r)
         r = .NewRow : r(0) = "jack" : .Rows.Add(r)
         r = .NewRow : r(0) = …
TnTinMN 418 Practically a Master Poster

You are out of luck with a color cursor using the built-in .Net functions.

From the documentation:

The Cursor class does not support animated cursors (.ani files) or cursors with colors other than black and white.

But why limit yourself to what is built-in?

Here is a class that you can use to create a cursor from a .Net Image.

Imports System.Runtime.InteropServices

Public Class Form1

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      'make cursor with the hotspot (click point) the top-right corner
      Dim mc As New MakeCursor( _
         MakeCursor.ScaleImage(PictureBox1.Image, _
                               MakeCursor.SystemCursorSize.Width, MakeCursor.SystemCursorSize.Height), _
                               MakeCursor.SystemCursorSize.Width, 0)
      Me.Cursor = mc.Cursor
   End Sub

End Class

''' <summary>
''' Allows creating as cursor from an image
''' </summary>
''' <remarks>True Cursor Size is stored in the "Tag" Property</remarks>
Public Class MakeCursor
   Implements IDisposable
   Private cursorptr As IntPtr

   ''' <summary>
   ''' creates cursor from an Image class
   ''' </summary>
   ''' <param name="img">Source Image for cursor</param>
   ''' <param name="HotSpot_x">the x coordinate of the click pt</param>
   ''' <param name="hotSpot_y">the y coordinate of the click pt</param>
   ''' <remarks></remarks>
   Public Sub New(ByVal img As Image, ByVal HotSpot_x As Int32, ByVal hotSpot_y As Int32)
      Dim cusorrinfo As New IconInfo
      Dim bm As Bitmap = CType(img, Bitmap)
      With cusorrinfo
         .fIcon = False 'cursor
         .xHotspot = HotSpot_x
         .yHotspot = hotSpot_y
         .hbmMask = bm.GetHbitmap
         .hbmColor = bm.GetHbitmap
      End With
      Dim cursorinfoptr As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(cusorrinfo))
      Marshal.StructureToPtr(cusorrinfo, cursorinfoptr, True)
      cursorptr = CreateIconIndirect(cursorinfoptr)
      Dim icon As Icon = icon.FromHandle(cursorptr)
      Cursor = New Cursor(cursorptr)
      Cursor.Tag = bm.Size
      Me.Size = bm.Size …
TnTinMN 418 Practically a Master Poster

Sorry for the late reply; I got distracted.
I have not experienced this blink issue. Can you post your project as a sip file, so that we can look it over. It may be an issue with your timer interval an/or your saving of the image.

TnTinMN 418 Practically a Master Poster

Have you tried the example in the documentation?
Click Here

TnTinMN 418 Practically a Master Poster

Another option is to use the Linq extensions on the array class.

For example:

   Dim A() As String = {"a", "b", "c", "d", "e"}
   Dim B() As String = {"a", "g", "c", "h", "k"}


   Dim InA_notIn_B() As String = A.Except(B).ToArray 'yields: b, d, e
   Dim InB_notIn_A() As String = B.Except(A).ToArray 'yields: g, h, k

'another way

   Dim CommonTo_A_and_B() As String = A.Intersect(B).ToArray 'yields: a, c
   Dim Union_A_and_B() As String = A.Union(B).ToArray 'yields: a, b, c, d, e, g, h, k

   Dim InA_notIn_BV2() As String = A.Where(Function(s As String) Not CommonTo_A_and_B.Contains(s)).ToArray 'yields: b, d, e
   Dim InB_notIn_AV2() As String = B.Where(Function(s As String) Not CommonTo_A_and_B.Contains(s)).ToArray 'yields: g, h, k
Reverend Jim commented: I just love new blood with new ideas +0
TnTinMN 418 Practically a Master Poster

This sounds like a case of fat fingers while playing a video game causing. ;)>

Yes, you can block the Windows Key via an application. It requires you to do a low level keyboard hook via the windows API's.

Imports System.Runtime.InteropServices

Public Class Form1
   'Choose either while running or while focused
   Private BlockingOption As BlockingOptions = BlockingOptions.WhileRuning

   Private Enum BlockingOptions
      WhileRuning
      WhileFormOrOneOfItsControlsIsFocused
   End Enum


   Private Event DontDoThat()
   Private Sub Form1_DontDoThat() Handles Me.DontDoThat
      MessageBox.Show("Don't press the windows key!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
   End Sub

   Private hook As New IntPtr
   Private Const VK_LWIN As UInt32 = &H5B 'Left WinKey
   Private Const VK_RWIN As UInt32 = &H5C 'Right WinKey
   Private Const WM_KEYDOWN As Int32 = &H100

   Private Delegate Function LowLevelKeyboardProc(ByVal nCode As Int32, _
                                                  ByVal wParam As Int32, _
                                                  <[In]()> ByVal lParam As IntPtr) As Int32

   Private KeyboardHookProcedure As LowLevelKeyboardProc



   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      KeyboardHookProcedure = New LowLevelKeyboardProc(AddressOf LLKeyboardProc)
      Dim lpdwProcessId As New IntPtr
      Dim modulehandle As IntPtr = GetModuleHandle(CStr(Nothing))
      hook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, KeyboardHookProcedure, modulehandle, 0)
   End Sub

   Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
      'make sure hook is released.  
      'It should timeout and become inactive is app closes without release, but
      'do it anyways.
      If hook <> IntPtr.Zero Then
         UnhookWindowsHookEx(hook)
      End If
   End Sub

   Public Function LLKeyboardProc(ByVal Code As Int32, ByVal msg As Int32, ByVal ptrTokbllStructure As IntPtr) As Int32
      'see: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644985(v=vs.85).aspx
      If Code >= 0 Then
         'its a code we can process
         'need to retrieve keyboard …
TnTinMN 418 Practically a Master Poster

Most of your needs are pretty straight forward. The adding a button one is the stickler. I've hosted other apps in a winform before, so I thought why not follow the same method to host a winform button in another app? It sort of works ok.

You need to control force repainting of the control as the other app will not do it for you. I used a timer to do this. Also, once the button is on the other app, if you click it, it gains focus and you need to send the focus back to the form from which it originated in its click event handler.

Start a new winform project:
Form1.vb code

Imports System.Runtime.InteropServices

Public Class Form1

   Private WithEvents Slave As Process
   Private Slave_SI As New ProcessStartInfo
   Private OldButtonLoc As Point
   Private WithEvents btn2Refresher As New Timer With {.Interval = 500}

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      Button1.Enabled = False
      With Slave_SI
         .FileName = "notepad.exe"
         .Arguments = ""
         .WindowStyle = ProcessWindowStyle.Normal
      End With
      Slave = Process.Start(Slave_SI)
      Slave.EnableRaisingEvents = True

      Slave.WaitForInputIdle(5000) ' give it 5 seconds to startup
      'add the button you wanted
      'will steal a button from this form
      SetParent(Button2.Handle, Slave.MainWindowHandle)
      'position the button
      OldButtonLoc = Button2.Location
      Button2.Location = New Point(50, 0)
      Button2.Visible = True
      btn2Refresher.Start() 'hack to repaint button on host window
      Me.ActiveControl = Me.Button3 'need to force focus back to a current form window
                                    'It jumped to button2 when I disabled Button1

   End Sub

   Private Sub Button2_Click(ByVal …
iFrolox commented: Useful post :) +1
Reverend Jim commented: good stuff here +9
TnTinMN 418 Practically a Master Poster

When the database doesn't have a password, it works perfectly. But when I give it a password ("OpenSesame") and change the Connect string to "Access;pwd=OpenSesame", I get this error:
"Couldn't find installable ISAM."

I am probably wrong on this, but shouldn't the connection string be: "dns=Access;pwd=OpenSesame"?

TnTinMN 418 Practically a Master Poster

The problem I'm having with the latest implementation is this: when saving a file in a local folder, about four extensionless files are created before finally saving the Excel document.

You may find this article to educational on this issue.
Click Here

TnTinMN 418 Practically a Master Poster

Resequencing the line numbers is fairly trivial. The issue is if there are any GOTO’s in the CNC code. Based on a quick internet search, a GOTO can be defined line number. The line number can be either directly specified or via a variable. Variables are prefixed with the hash “#” symbol followed by an integer.
For example:

N100
GOTO 100

100=100

GOTO #100

To remap the GOTO statements, I used a dictionary (of int32, int32) where the key value is the N####’s original numeric value. It allows looking up the original value and retrieving the new line number. In the code that follows, only variables used in a GOTO statement will be treated as line numbers and be remapped to the new line number. To test this logic, I added these lines to the end of your example.

    #100=1000
    #101=1000
    #101=1040
    GOTO #101
    GOTO 100

There appears to be other types of GOTO's used in CNC code (GOTOF, GOTOB), if you need to account for these, you can follow the pattern demonstrated in my code.

Here is the code. It writes the original code followed by the resequenced code to a RichTextBox.

Public Class Form1

   Private Const fmt As String = "0000"

   'a class to assist in storing info about lines that define a variable
   'variable start with a '#' followed by an integer
   Private Class VariableLine
      Public Name As Int32
      Public LineNumber As Int32 'the line of code that contains the declaration …
TnTinMN 418 Practically a Master Poster

The WebBrowser control uses the installed IE. The problem is that IE8 and above will default to IE7 standards mode. To enable the newer standards, you need to make a registry entry for you specific application executable.

See: Click Here

Click Here

TnTinMN 418 Practically a Master Poster

Add this to your code right after the "CopyFromScreen".

      Cursor.Current.Draw(GraphX, New Rectangle(Point.Subtract(Cursor.Position, New Size(Cursor.Current.HotSpot.X, Cursor.Current.HotSpot.Y)), Cursor.Current.Size))

I hope that you are calling Dispose on GraphX when you are done with it.

TnTinMN 418 Practically a Master Poster

Hi Jim,

If I'm understanding your problem correctly, I think what you want is a message prefilter. These filters are added to the application and filter all application messages. By combining WM_MOUSEMOVE and WM_MOUSELEAVE with a hit test on the clientrectangle you can achieve this.

Public Class Form1
   Implements IMessageFilter
   Private Const WM_MOUSELEAVE As Int32 = &H2A3
   Private Const WM_MOUSEMOVE As Int32 = &H200
   Private MouseInForm As Boolean = False
   'Add a dock-filled panel to the form to block the normal MouseLeave, MouseEnter Events
   Private pnl As New Panel With {.Dock = DockStyle.Fill, .Parent = Me, .BorderStyle = BorderStyle.Fixed3D}

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


   Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
      If m.Msg = WM_MOUSELEAVE OrElse m.Msg = WM_MOUSEMOVE Then
         'hit test the client rectangle
         'since WM_MOUSELEAVE does not provide the mouse location, use MousePosition
         Dim hit As Boolean = Me.ClientRectangle.Contains(Me.PointToClient(MousePosition))
         If hit Then
            If Not MouseInForm Then
               OnMouseEnter(Nothing)
            End If
            MouseInForm = True
         Else
            If MouseInForm Then
               OnMouseLeave(Nothing)
            End If
            MouseInForm = False
         End If
      End If
   End Function

   Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
      Application.RemoveMessageFilter(Me)
   End Sub

   Private Sub Form1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseEnter
      Debug.WriteLine("mouse entered form")
   End Sub

   Private Sub Form1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseLeave
      Debug.WriteLine("mouse left form")
   End Sub
End Class
TnTinMN 418 Practically a Master Poster

Hi kRod,

In terms of speed the Linq method will be the slowest as it will search against every record in the list. If you use Redgate's Reflector to inspect the code that executes for the other three methods, you find that at the end of the call tree that they all enumerate sequentially through the list. Their only saving grace is that once a match is found, they stop searching.

Based on the class compareto method, you are defining equality based solely on the extension field. Is each extension in the list unique? If so, then using a dictionary would give you better search performance.

TnTinMN 418 Practically a Master Poster

It appears that you are trying to convert the reader item directly into a byte array. Everything I've seen on using the Oracle library uses the OracleBlob type to extract the data. The following demonstrates the code pattern.

Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types

Public Class Form1

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

      Dim cn As New OracleConnection("your connection string")
      cn.Open()

      Dim cmd As New OracleCommand("Select Pk, Pic From PicTable Where PK=Something", cn)
      Dim rdr As OracleDataReader = cmd.ExecuteReader
      Dim RecordFound As Boolean = rdr.Read
      'Item 1 is the pic item
      If RecordFound AndAlso rdr.Item(1) IsNot Nothing Then

         Dim blob As OracleBlob = rdr.GetOracleBlob(1)
         Dim blobbytes(CInt(blob.Length)) As Byte
         blob.Read(blobbytes, 0, CInt(blob.Length))
         'create a new memory stream initialized with blobbytes
         Dim ms As New IO.MemoryStream(blobbytes)
         Dim pic As Image = Image.FromStream(ms)
         ms.Close()
      End If
      cn.Close()

   End Sub
End Class
TnTinMN 418 Practically a Master Poster

To answer your question of controling the ReSize event logic, how about something like this:

   Private DoneLoading As Boolean = False

   Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      'your code
      DoneLoading = True
   End Sub

   Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
      If DoneLoading Then ScreenResize()
   End Sub
TnTinMN 418 Practically a Master Poster

Hi Toomutch,

Is there a specific reason for wanting the distance from the edge as a percentage of the form size?
If you can accept having the sides at a constant distance from the edge, you can use the Control.Anchor property to achieve this. For the case of your datagridview, you could anchor to to the left,top, and right of the form. This will cause the dgv to resize with the form.
anchor2

Edit: I seen that you also have a set distance from the bottom, so anchor to the bottom as well.

TnTinMN 418 Practically a Master Poster

The SQL date functions will pull the date from the computer acting as the DB server. It may not be appropriate to use the server's date for the comparison unless it is also used to set the transaction date field.

TnTinMN 418 Practically a Master Poster

I would do the changes on the CellValueChanged event.

For this example, I have assumed that there is a datagridview column named "Column3" and that you are testing against an integer value. Make changes to column name and field type as necessary to match your data.

Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
      'exit if not the target column
      If DataGridView1.Columns(e.ColumnIndex).Name <> "Column3" Then Exit Sub
      'since we know the column is the correct one, can use e.ColumnIndex
      'to reference the cell of interest
      Dim testvalue As Int32
      Try
         'make sure the value can be converted to the proper type
         testvalue = CType(DataGridView1(e.ColumnIndex, e.RowIndex).Value, Int32)
         If testvalue = 3 Then
            DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.AliceBlue
         Else
            If DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor <> DataGridView1.RowsDefaultCellStyle.BackColor Then
               'set to the default
               DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = DataGridView1.RowsDefaultCellStyle.BackColor
            End If
         End If
      Catch ex As Exception
         'no big deal for this example, not as I am not validating input
         Exit Sub
      End Try
   End Sub
TnTinMN 418 Practically a Master Poster

could you also show the code where you retrieve the blob and fill imagedata?

TnTinMN 418 Practically a Master Poster

What type of database are you using? You indicate the SQL Date type; to me this implies possibly a MySQL DB. If it is a MS SQL Server DB, the type is probably a datetime type. If this is the case then your data may contain a time component that is causing your search to fail.

Another possibility is how you are defining the search key value. If you use the MonthCalendar.SelectionStart property, there should not be a problem. If you are entering the date as string, you could be encountering a culture format issue.

Based on your "3.7.2012" format, I assume that you mean "3 July 2012". Assuming your data has a record for "3 July 2012", this code should work if: System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern ="dd.MM.yyyy"

      Dim d As Date = CDate("3.7.2012")
      Dim r As DataRow = dt.Rows.Find(d)

However this code will search for "7 March 2012" as it uses the invariant culture to covert the string to a date.

      Dim r As DataRow = dt.Rows.Find("3/7/2012")

I knew this was the case when using an expression filter (DataTable.Select(filter)) as it is stated in the documentation that this is so, but their is no corresponding comment for the DataRow.Find method (thankyou very much MS). I had to discover this the hard way.

TnTinMN 418 Practically a Master Poster

I'm NOT buying another version to do something so simple

Have you never heard of the free express editions? Granted you do not get all the bells and whistles of the full VS suite, but they do offer a full implimentation of the language.

Visual Basic 2005 Express Edition (445,282 KB)
* IMG File (http://go.microsoft.com/fwlink/?linkid=54764)
* ISO File (http://go.microsoft.com/fwlink/?linkid=57033)

Visual Studio 2008 Express Editions
http://www.microsoft.com/visualstudio/en-us/products/2008-editions/express

Visual Basic 2010 Express
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express

Ok, here's the deal... When I attempt to use the form name, I do NOT get the option to open my form. I have to declare it somewhere first. Right now, that declaration is made in a module so that the form is global (I need to call a sub on this form from another form). What would you suggest I do?

Perhaps, it it not really an issue of whether the form is currently visible, but rather one of how to reference your instance of that form?

Public Class Form1
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      ModTest.frmTest.TheOneIWant()
   End Sub
End Class

Public Module ModTest
   Public frmTest As New Testform
   Public Class Testform
      Inherits Form
      Public Sub TheOneIWant()
         MsgBox("yep, I'm here")
      End Sub
   End Class
End Module
TnTinMN 418 Practically a Master Poster

What i had in mind was saving it as ini file, encrypting the file to another extension, and encrypt it to binary, but to do that i would use the special folder in the AppData, is there a better way for me to save the arrays and encrypt it and be able to read it again and load it in my application?

Hi,

I don’t know if this is a better way, but I’ll leave it to you to decide. It totally changes the way you are managing your data.

Basically what you have is a set of account records that you wish to store and retrieve. You also want to obfuscate the data so users can not see sensitive data.

Two alternatives that immediately come to mind are first a database and second one is to store the data in a user-setting. Personally, I would opt for the database, but some people some to find them to be difficult to work with particularly in getting them stored in the proper location so that they can be written back to without bumping into security issues. The user-setting option alleviates the issue of dealing with the file location as .Net will handle this for you, so that is the route that I plan to show you below.

Since your have a defined Account record format, it makes sense to use a datatable to store each record. You can add a datatable to the user-settings as shown in the this …

TnTinMN 418 Practically a Master Poster

Is it possible that the data type for both qtyinstock and critical are string (nvarchar)? That would explain the results.

If it is then perhaps this will work:

select ProductCode, ProductName, qtyinstock, critical from product where Cast(qtyinstock AS int) <= Cast(critical as int)

TnTinMN 418 Practically a Master Poster

Hi Dave,
I suggest that you either type "Option Strict On" as the first line in your code or enable as the default state under "Options->Projects and Solutions->VB Defaults". This will force VS to flag improper type conversions. It may seem like a pain at first, but you will find that fixing the errors it finds will save you many headaches down the road.

You also have an error in your distance calculation. For reference, see Click Here
V(t) = at + c1; where V(t) = velocity at time t, a = acceleration, t = time, and c1=constant.
Subjecting this equation to the boundary condition of V=0 at t=0, leads to c1=0
V(t) = a
t
The position (or distance) formula is:
p(t) = (at^2)/2 + c1t + c2
but c1 = 0 and at t=0, p(0) = 0, therefore c2 = 0
p(t) = (a*t^2)/2

I have restructured your code to show you a more conventional way of doing what your code is doing. You do not need a method for each airplane; just use the arrays you defined and do an array lookup on the name.

Public Class Aircraft
   'as this data is common and constant, declare it as shared.
   Private Shared Names() As String = {"A-747", "A-737", "C-150", "D-240"}
   Private Shared TakeOffVelocity() As Double = {250, 264, 270, 240}
   Private Shared Acceleration() As Double = {33.5, 44.2, 37.1, 51.9}

   'there is nothing unique about the calculation either. …
TnTinMN 418 Practically a Master Poster

Is there a specific reason for developing in such an outdated version of VB?
If you could update to more recent VB version, you could make use of the My.Application.OpenForms collection. I believe the My namespace became available in VB2005.

TnTinMN 418 Practically a Master Poster

Would you please add some comments/documentation as to what this code is doing other than "look for inconsistencies" and "invokes a reordering logic"? Your code is appreciated but it would be even better if the mechanics were explained.

Jim,
I did not realize that it was as requirement of this site to post fully documented code.

I also did not realize that I was presenting anything that complex and it was not my intent to offer that code as a solution, but rather an example to continue the discussion that I had started with the OP that a simple sort was probably not a good idea as it could easily make a bad situation worse.

Oh well, live and learn. In complying with your request, I found a few logic mistakes that are now corrected in the code below. I suppose that I should state that to use this code one should open a new WinForm project in visual studio. Add two buttons and a richtextbox to Form1. Open the Form1.vb file in code view and replace the code found there with that shown below.

Public Class Form1

   Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      'Read in the CNC code file
      Dim fs As New IO.FileStream("code.txt", IO.FileMode.Open)
      Dim sr As New IO.StreamReader(fs)

      'Read lines into a stringbuilder. 
      'This is a waste of memory, but will speed up loading
      'could prevent RTB from repainting and append directly to RTB, but do not …
TnTinMN 418 Practically a Master Poster

It sounds like the logic is alreagy becoming more complex than a simple sorting based on N###. I have put together a simple demo program, that offers two options. Button1 will look for inconsistencies based on N### and present the offending block to the user for editing. Button2 invokes a reordering logic based on N###, but this type of logic is prone to failure as there is no way a programmer can forsee every possible mistake a human can make in coding and automatically correct it.

Public Class Form1

   Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      Dim fs As New IO.FileStream("code.txt", IO.FileMode.Open)
      Dim sr As New IO.StreamReader(fs)

      Dim sb As New System.Text.StringBuilder(CInt(fs.Length))
      Do Until sr.EndOfStream
         sb.AppendLine(sr.ReadLine)
      Loop
      sr.Close()
      With RichTextBox1
         .WordWrap = False
         .ScrollBars = RichTextBoxScrollBars.ForcedBoth
         .Text = sb.ToString
         .HideSelection = False
      End With
   End Sub

   Sub OrderOnN_Numbers()
      Dim ErrorExists As Boolean = False
      Dim lastNumber As Int32 = -1
      Dim currentNumber As Int32
      Dim BadnumberRef As LineNumberRef = Nothing

      Dim NumberIndices As New List(Of LineNumberRef)
      Dim lines() As String = RichTextBox1.Lines
      Dim l As String
      Dim index As Int32
      For i As Int32 = 0 To lines.Count - 1
         l = lines(i).Trim
         If l.StartsWith("N") Then
            index = l.IndexOf(" ", 1)
            currentNumber = -1
            If index = -1 Then
               Int32.TryParse(l.Substring(1), currentNumber)
            Else
               Int32.TryParse(l.Substring(1, index - 1), currentNumber)
            End If

            If currentNumber <> -1 Then
               If lastNumber >= currentNumber Then 'error

                  If Not ErrorExists Then
                     BadnumberRef = New LineNumberRef(lastNumber, i)
                     With RichTextBox1
                        .SelectionStart = .GetFirstCharIndexFromLine(i) …
TnTinMN 418 Practically a Master Poster

Hi,
I have added a converter from string to Matrix to your Matrix class. I have also modified your code a bit so that it can run. You Matrix.ToString method returns a multi-line string, so make sure that the textboxes are multiline and big enough to see three lines.

The string converter does minimal error checking, so you may want to improve on that shown. It allows you to separate the matrix values using NewLine, comma, or space characters.

Public Class Form1
    Dim a1 As New Matrix3x3
    Dim b1 As New Matrix3x3
    Dim c1 As New Matrix3x3

    Dim rand As New Random

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      Dim m As New Matrix3x3
      Dim n As New Matrix3x3
      For row As Integer = 0 To 2
         For col As Integer = 0 To 2
             m.Item(row, col) = ((row * 3) + col)
             n.Item(row, col) = rand.Next(0, 2000)
         Next
      Next

      a1 = "1,1,1,1,1,1,1,1,1"
      TextBox1.Text = a1.ToString

      b1 = "2,2,2,2,2,2,2,2,2"
      TextBox2.Text = b1.ToString

      c1 = a1.Add(b1)

      TextBox3.Text = c1.ToString
    End Sub

End Class


Public Class Matrix3x3

    Private m_values(8) As Integer

    Sub New()
        ' initialise array:
        m_values = New Integer(8) {}
    End Sub
    ' expose a member of the array:
    Public Property Item(ByVal index As Integer) As Integer
        Get
            If index < 0 Or index > 8 Then Throw New ArgumentOutOfRangeException
            Return m_values(index)
        End Get
        Set(ByVal value As Integer)
            If index < 0 Or index > 8 Then Throw New ArgumentOutOfRangeException
            m_values(index) = value
        End …
TnTinMN 418 Practically a Master Poster

Are you sure that sorting based on N#### is really the best logic?
In your sample file, there appears to be condition statements defined after the N####.
i.e.

N1040 IF (LAST_TOOL <> 0)
N1050 WHEN TRUE DO $R21=1
N1060 T1=LAST_TOOL
N1070 GOTOF (<<"T_"<<LAST_TOOL)
N1080 ENDIF

A typo in the N#### followed by sorting could easily change the logic of the CNC program. Would it not be better to make your program a validator/editor that requires human input to check the logic when inconsistencies are found?

TnTinMN 418 Practically a Master Poster

I have no idea what is causing your issue, but this VBA code works fine for me from Excel.

Private Declare Function SetEnvironmentVariable Lib "kernel32" Alias "SetEnvironmentVariableA" _
                        (ByVal lpName As String, ByVal lpValue As String) _
                        As Long

Sub test()
    Dim env As Long
    env = SetEnvironmentVariable("somethingnew", "Hello")

    Dim res As Integer
    res = Shell("CMD /k echo %somethingnew%", vbNormalFocus)

    'somethingnew will be set for the cmd window created above,
    'eventhough this next line deletes it from the system

    env = SetEnvironmentVariable("somethingnew", "")

End Sub
TnTinMN 418 Practically a Master Poster

Assuming that you intended to replace the text in the textbox with the trimmed text,

   Dim index As Int32
   Dim trimmedtext As New System.Text.StringBuilder(TextBox1.Text.Length)
   For i As Int32 = 0 To TextBox1.Lines.Length - 1
      index = TextBox1.Lines(i).IndexOf("@")
      If index <> -1 Then
         'add trimmed line characters
         trimmedtext.Append(TextBox1.Lines(i), 0, index)
      Else
         trimmedtext.Append(TextBox1.Lines(i))
      End If
      trimmedtext.Append(vbCrLf)
   Next
   TextBox1.Text = trimmedtext.ToString
TnTinMN 418 Practically a Master Poster

If you have your heart set on gray, then maybe this?

   Dim bc As Color = Me.BackColor
   Me.BackColor = Color.LightGray
   Form2.ShowDialog()
   Me.BackColor = bc

Or if you just want to dull the current backcolor up a bit

   Dim bc As Color = Me.BackColor
   Dim DullFactor As Single = 0.25 'Roange from 0 to 1.  Closer to zero = duller
   Me.BackColor = Color.FromArgb(255, CInt(Me.BackColor.R * DullFactor), CInt(Me.BackColor.G * DullFactor), CInt(Me.BackColor.B * DullFactor))
   Form2.ShowDialog()
   Me.BackColor = bc