Quantcast
Channel: VBForums - Visual Basic .NET

Ltrim to trim textbox

0
0
hi. I have a question. I have a form with a textbox which contains a line of text like this

abcdefg@hijklmnop.

Is it possible to use Ltrim to remove everything up to the @ symbol I've googled it but i can't find anything that will what i need.

all help would be appreciated.

Using a module

0
0
I have a project that has 3 forms. All 3 forms uses different data from 1 datatable. Is it possible to creat and load data to that datatable in a module and access that data from my forms. I have never used a module before so I’m not sure how that works. Thanks…

[RESOLVED] Adding System.Windows.Forms to .Net 8 dll

0
0
From everything I have seen, this should be possible, but for some reason, I haven't been able to add System.Windows.Forms to a .Net 8 class library project. I need to add a custom cursor, which is the immediate issue, but I realized I will eventually want to add a form to this class library. I would have thought that I could add this through NuGet, but it isn't showing up. All I'm seeing online makes it seem like this should be nothing special. There aren't any instructions, because there clearly don't need to be, yet I'm not seeing it.

What am I missing?

Calling .NET 8 Windows Class Library from .NET Framework Project

0
0
I've been playing around with a way to dynamically load .NET Core dlls from a .NET Framework project. It has been interesting.

The .NET 8 project currently has this in it:

Code:

Public Shared Function LoadCoreRearingUnitPlugins(fileName As String) As Type()
    Dim asmbl = Assembly.LoadFrom(fileName)
    If asmbl IsNot Nothing Then
        Return asmbl.GetExportedTypes
    Else
        Return New Type() {}
    End If

End Function

Originally, I passed in a System.Reflection.Assembly object, but there was a significant change between the Framework version of that object and the Core version of the object. The code I put into the Framework project can be condensed down to this:

Code:


Private Sub LoadShapes()

 Dim aDLL As System.Reflection.Assembly = System.Reflection.Assembly.LoadFile(fl)

 If aDLL IsNot Nothing = Nothing Then
    Dim tArr As Type()
    Try
        tArr = aDLL.GetExportedTypes
    Catch ex As System.IO.FileNotFoundException
        tArr = CoreLoader.LoadMethods.LoadCoreRearingUnitPlugins(fl)
        Continue For
    End Try

'Etc.

This is right off in a method that gets called from elsewhere. I found that if I loaded a Core dll using that code, then aDLL.GetExportedTyppes would throw a FileNotFoundException (or possibly something else, I realize I haven't fully validated that). The way I originally had LoadCoreRearingUnitPlugins working, the call would be made, but would immediately fail. I was passing aDLL to the method, and the difference between the Framework Assembly and the Core Assembly broke the code.

Therefore, I figured I could pass the file name to the method, and changed the method so that it loads the assembly itself (as shown in the first code snippet). By doing that, I would get the Core version of Assembly, not the Framework version. That seemed like a good idea, but it failed in a way I have never actually seen code fail before.

I can't even step into the LoadShapes method. Even the attempt to call the method throws a FileNotFoundException. I can't even step into the first, innocent, line. This is because of the call to LoadCoreRearingUnitPlugins. I have confirmed that because the code works fine so long as I comment that code out. Note that the code DID work, until I added the reference to System.Reflection.Assembly to the Core project. So, it was adding that reference that means the very call to LoadShapes throws an exception. The code doesn't even make it to the first line if that call to LoadCoreRearingUnitPlugins is found anywhere in the function.

I'm not sure what to make of this, and whether there is any way to get around it. A Framework project can reference a Core dll, but if that Core dll references System.Reflection.Assembly, then a method in the Framework project that includes a call to the Core dll appears to throw an exception.

The ultimate goal was to be able to mix and match dynamically loaded dlls from either Core or Framework. I was thinking it wasn't possible, but I thought I had found a way around it by letting the Framework project load Framework plugins and have a Core project that loaded Core plugins. It's looking like doing so just isn't possible.

Any suggestions?

VS Code SQL help pls

0
0
Hi there,

I recently started using VB.NET and doing my first VB/SQL project.

I have very basic question.

In VB 6 I used to get the last record result through below SQL (OleDB)

Dim LastRecord as Integer
adoPrimaryRS1.Open "Select * from BUY ORDER BY ID ASC", dB4, adOpenStatic, adLockOptimistic
adoPrimaryRS1.MoveLast
LastRecord = adoPrimaryRS1.Fields!Id

and now I am using SQL Server client, could you please tell me how to achieve above. I am using the below code.


Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 1 ID FROM dbo.Accounts ORDER BY ID DESC", CON)
Dim DA As New SqlDataAdapter(cmd)
Dim DT As New DataTable

Many thanks in advance.

Kh

textbox select first character

0
0
hi! i'm trying to select the first character in a textbox. is this doable?

Context menu issue

0
0
The following code works fairly well but the context menu strip associated with listbox1 works even when right clicking in a blank space in listbox1.

What needs to change so that the context menu comes up only when a line item is clicked?

Code:

Imports System.Windows.Forms

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Create context menu strip
        Dim contextMenuStrip1 As New ContextMenuStrip()

        ' Add items to the context menu
        Dim menuItem1 As New ToolStripMenuItem("Edit")
        AddHandler menuItem1.Click, AddressOf EditMenuItem_Click
        contextMenuStrip1.Items.Add(menuItem1)

        Dim menuItem2 As New ToolStripMenuItem("Delete")
        AddHandler menuItem2.Click, AddressOf DeleteMenuItem_Click
        contextMenuStrip1.Items.Add(menuItem2)

        ' Assign the context menu to the ListBox
        ListBox1.ContextMenuStrip = contextMenuStrip1

        ' Add items to the listbox
        ListBox1.Items.Add("Subject item:= 1")
        ListBox1.Items.Add("Name item:= 2")
        ListBox1.Items.Add("Listing item:= 3")
        ListBox1.Items.Add("Showing item:= 4")
    End Sub

    Private Sub EditMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox(ListBox1.Items(ListBox1.SelectedIndex))
    End Sub

    Private Sub DeleteMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox(ListBox1.Items(ListBox1.SelectedIndex))
    End Sub

    Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
        If e.Button = MouseButtons.Right Then
            Dim index As Integer = ListBox1.IndexFromPoint(e.Location)
            If index >= 0 Then
                ListBox1.SelectedIndex = index ' Select the item
                ListBox1.ContextMenuStrip.Show(ListBox1, e.Location)
            End If
        End If
    End Sub

End Class

VS 2022 [RESOLVED] VB.net: "IndexOutOfRangeException" Error Querying SQLite DB

0
0
I'm not sure if I need to re-code something here. The database is SQLite, and I'm using System.Data.SQLite as the provider.

I call the following function to populate ComboBox objects throughout my application, and have a similar one for ListBox objects:
Code:

Public Function FLBG_PopulateComboBox(
        ByVal _ComboBoxObject As Object,
        ByVal _DataSource As String,
        ByVal _TableName As String, ByVal _SelectFilter As String,
        Optional ByVal _SearchFilter As String = "",
        Optional ByVal _SortFilter As String = ""
        ) As Boolean
    Dim fnReturnValue As Boolean                                                        ' Return value
    Dim fnSQLConnection As SQLiteConnection                                            ' SQLite connection
    Dim fnSQLCommand As SQLiteCommand                                                  ' SQLite command
    Dim fnSQLReader As SQLiteDataReader                                                ' SQLite data reader
    Dim fnSQLQuery As String                                                            ' SQLite query string

    fnReturnValue = True                                                                ' Set exit status
    fnSQLQuery = "SELECT " & Trim(_SelectFilter) & " FROM [" & _TableName & "]"        ' Build SQL query
    If Len(Trim(_SearchFilter)) > 0 Then fnSQLQuery = fnSQLQuery & " WHERE " & _SearchFilter
    If Len(Trim(_SortFilter)) > 0 Then fnSQLQuery = fnSQLQuery & " ORDER BY " & _SortFilter
    If fnSQLQuery.Substring(fnSQLQuery.Length - 1) <> ";" Then fnSQLQuery &= ";"        ' Terminate SQL query

    fnSQLConnection = New SQLiteConnection(_DataSource)                                ' SQLite data source
    fnSQLCommand = fnSQLConnection.CreateCommand()                                      ' Create command placeholder

    fnSQLConnection.Open()                                                              ' Open connection
    fnSQLCommand.CommandText = fnSQLQuery                                              ' Get configuration directive
    fnSQLReader = fnSQLCommand.ExecuteReader()                                          ' Execute table reader
    If fnSQLReader.HasRows Then                                                        ' If the table is not empty:
        While fnSQLReader.Read                                                          ' - Read a record
            _ComboBoxObject.items.add(fnSQLReader(_SelectFilter).ToString)              ' - Add record to object
        End While                                                                      ' - Repeat till done
    Else
        fnReturnValue = False                                                          ' Update exit status
    End If
    fnSQLReader.Close()                                                                ' Close table reader
    fnSQLConnection.Close()                                                            ' Close connection

    Return fnReturnValue
End Function

It works perfectly when invoked against a single column, or concatenated of columns as a simple query. For example:
FLBG_PopulateComboBox(cmbFileType, appSQLDataSource, "Extensions", "Extension",, "[Extension] COLLATE NOCASE ASC")
or
FLBG_PopulateComboBox(cmbFormatDetail, appSQLDataSource, "FilmInfo", "[Brand] || ' ' || [Series] || ', ISO ' || [ISO]",, [Brand] COLLATE NOCASE ASC, [Series] COLLATE NOCASE ASC, [ISO] ASC)

But when the query is more complex, meaning it has a condition built into the SELECT, I get a "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" error instead. Take the following table containing test data, and its associated call :
Name:  capture.png
Views: 148
Size:  3.2 KB
Code:

Dim _SelectFilter As String = "[SeriesName],[SubsetName],CASE " &
                              "WHEN LENGTH(TRIM([SubsetName])) > 0 THEN [SeriesName] || '/' || [SubsetName] " &
                              "ELSE [SeriesName] END AS [CollectionName]"
Dim _SortFilter As String = "[SeriesName] COLLATE NOCASE ASC, [SubsetName] COLLATE NOCASE ASC"
FLBG_PopulateComboBox(cmbSetName, appSQLDataSource, "Series", _SelectFilter,, _SortFilter)

While VB.net raises the aforementioned error, the generated query works perfectly fine in the SQLite Expert Personal 5.5 SQLite Database browser). That code is SELECT [SeriesName],[SubsetName],CASE WHEN LENGTH(TRIM([SubsetName])) > 0 THEN [SeriesName] || '/' || [SubsetName] ELSE [SeriesName] END AS [CollectionName] FROM [Series] ORDER BY [SeriesName] COLLATE NOCASE ASC, [SubsetName] COLLATE NOCASE ASC;, and returns:
Name:  capture.png
Views: 142
Size:  3.4 KB

I'm unsure whether the cause is in in the VB.net code or on the SQL query. Therefore, I see two possibilities:

  1. The issue is how I'm querying for vs. how the results are being returned, but the result I need is how it appears in the aliased column (CollectionName). In this case, I'm unsure what adjustment the function requires. Ideally it should work regardless of whether the parameters generate a simple or complex query. However, I have no qualms about using a separate function just for complex queries if necessary. Either way, it has to be reusable, meaning the alterations come in as parameters instead of being hard-coded.
  2. The issue is in the query after all, and SQLite Expert ignores that error. But if this is the case, I'm at a loss as to what exactly is triggering the error. Similarly, it could be something in the Provider that is keeping legitimate SQL code from running.

Either way, I could use some input here...
Attached Images
  

VS 2022 [RESOLVED] Timer Plus Sound (.wav)

0
0
Hello everyone.

I am working on a timer which can be used as a quiz bee timer, count down, count up timer, and stopwatch. Right now, I am having a problem playing a .wav playing while timer is counting (for quiz bee purposes). I want to play a ticking sound and at the desired stop time, a chime sound will also play. Here is what I have so far.

Code:

Private sonarSound As System.Media.SoundPlayer ' Declare a class-level variable to store the sonar sound player object
    Private chimeSound As System.Media.SoundPlayer ' Declare a class-level variable to store the chime sound player object
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
      Try
            ' Update the stopwatch display every tick
            Dim elapsedTime As TimeSpan = DateTime.Now - startTime
            Dim formattedTime As String = elapsedTime.ToString("hh\:mm\:ss\.f") ' Format includes milliseconds

            ' Play sonar sound every tick if enabled
            If isRunning AndAlso isSoundEnabled AndAlso ChkSound.Checked Then
                If elapsedTime.Seconds Mod 1 = 0 Then
                    PlaySonarSound() ' Play the sonar sound
                End If
            End If

            LblTime.Text = formattedTime

            ' Check if it's time to stop the timer
            If DateTime.Now >= stopTime Then
                isRunning = False
                BtnStartStop.Text = "Start"
                Timer1.Stop()
                If ChkSound.Checked Then
                    PlayChimeSound() ' Play the chime sound
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("An error occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub PlaySonarSound()
        Try
            ' Check if the sonar sound player is not already initialized
            If sonarSound Is Nothing Then
                sonarSound = New System.Media.SoundPlayer("C:\Users\epr06\source\repos\Lakay'sTimer\Lakay'sTimer\sonar.wav")
            End If
            ' Play the sonar sound asynchronously
            sonarSound.Play()
        Catch ex As Exception
            MessageBox.Show("An error occurred while playing the sonar sound: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub PlayChimeSound()
        Try
            ' Check if the chime sound player is not already initialized
            If chimeSound Is Nothing Then
                chimeSound = New System.Media.SoundPlayer("C:\Users\epr06\source\repos\Lakay'sTimer\Lakay'sTimer\chime_up.wav")
            End If
            ' Play the chime sound asynchronously
            chimeSound.Play()
        Catch ex As Exception
            MessageBox.Show("An error occurred while playing the chime sound: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

Attached Images
 

how to show data in a table in txt file

0
0
Hello,

I have the following code that creates the data in txt file.
I also attached the txt file.in this txt file there are different fields such as von, bis, name, id,...
each data is a list of these properties: von, bis, name, id,...
now these data are simple in txt file. how can i create a table in txt file and then insert data in this table.log2.txtlog2.txt



Code:

For Each Ereignissuchesettings In EreignissucheLog.EreignissucheSettings
    writer.Write(vbTab)
    writer.WriteLine(Ereignissuchesettings)
Next

the following code is also the property for settings.

Code:

Public ReadOnly Property EreignissucheSettings As New List(Of String)

Public Sub AddEreignisSettings(EreignisSettings As EreignissucheSettings)
    EreignissucheSettings.Add(EreignisSettings.CatZeitraum.ToString())
    EreignissucheSettings.Add(EreignisSettings.Gefahrenart.ToString())
    EreignissucheSettings.Add(EreignisSettings.CatGrenze.ToString())
    EreignissucheSettings.Add(EreignisSettings.Kovariablen.ToString())
End Sub

Attached Files

VS 2019 Process faster in nested for loops

0
0
Hi All,

I have 2 for loops which has data has array I need to compare one 1 item with rest all entries.
Example
Redim Temparray1(50000,18)
Redim Temparray2(50000,18)
Both arrays contains same data i need to pick 1st item from temparray1 and compare with 2nd item to 50,000 this is repeated.Below is the sample code.
Kindly help me in providing solution or best approach which will be faster

For j=0 to 50000

For m=j+1 to 50000

If temparray1 (j,0)=Temparray2 (m,0) then

End if


Next
Next

Thanks,
Sampath

Item Highlight in Listview on right click

0
0
Hi Team,

I have enabled multiselect for Listview. When I select multiple items and right click for a popup menu, the blue highlight on selected items goes off. I want to keep the selected items highlighted on right click. Can anyone please help me understand how to do this?

how to set the size of the header as the smae as the data in streamwriter

0
0
Hello,

I have the following code and the header are not in the same position of the data. do you have idea how to solve it?
I attach also the file test2.txt

Code:

    Using sfd As New SaveFileDialog()
        sfd.Filter = "Textdateien (*.txt)|*.txt"
        If sfd.ShowDialog(Me) = DialogResult.OK Then
            Using writer = New StreamWriter(sfd.FileName, False)
                writer.WriteLine(L("{0} Meldungen:", EreignissucheLog.Meldungen.Count))
                For Each meldung In EreignissucheLog.Meldungen
                    writer.Write(vbTab)
                    Select Case meldung.Art
                        Case PlanetMessage.Severity.Hinweis
                            writer.Write(L("Hinweis"))
                        Case PlanetMessage.Severity.Warnung
                            writer.Write(L("Warnung"))
                        Case PlanetMessage.Severity.Fehler
                            writer.Write(L("Fehler"))
                    End Select
                    writer.Write(vbTab)
                    writer.Write(meldung.Zeitstempel.ToString)
                    writer.Write(vbTab)
                    writer.WriteLine(meldung.Nachricht)
                Next
                writer.WriteLine()
                writer.WriteLine(L("{0} Liste von Ereignise:", EreignissucheLog.Ereignisinfoliste.Count))
                writer.Write(vbTab)
                'writer.WriteLine("Bis" & vbTab & "Ereignisname" & vbTab & "EreignisID" & vbTab & "Von" & vbTab & "Schadenaufwand" & vbTab & "Gefahrenart")
                writer.Write("Bis          " & vbTab)
                writer.Write("Ereignisname" & vbTab)
                writer.Write("EreignisID" & vbTab)
                writer.Write("Von" & vbTab)
                writer.Write("Schadenaufwand" & vbTab)
                writer.WriteLine("Gefahrenart")
                For Each Ereignis In EreignissucheLog.Ereignisinfoliste
                    writer.Write(vbTab)
                    writer.Write(Ereignis.Bis.ToString() & vbTab)
                    writer.Write(Ereignis.Er.Ereignisname & vbTab)
                    writer.Write(Ereignis.Er.EreignisID & vbTab)
                    writer.Write(Ereignis.Von & vbTab)
                    writer.Write(Format(Ereignis.Schadenaufwand, "0.0000") & vbTab)
                    writer.WriteLine(Ereignis.Er.Gefahrenart)
                Next
                writer.WriteLine()
                writer.WriteLine(L("{0} Ereignissuchesettings:", EreignissucheLog.EreignissucheSettings.Count))
                For Each Ereignissuchesettings In EreignissucheLog.EreignissucheSettings
                    writer.Write(vbTab)
                    writer.WriteLine(Ereignissuchesettings)
                Next
            End Using
        End If
    End Using

Attached Files

Tooltip does not appear sometimes: Windows Forms

0
0
In my VB.NET application, I utilize Windows Forms ToolTip on some controls. However, while hovering over a control, sometimes tooltip appears and sometimes not. I have searched online and found a solution suggesting to add the following two lines in the MouseEnter event.

_tooltip.Active = false;
_tooltip.Active = true;

However, implementing this solution did not resolve the issue. Are there any alternative approaches available to address this problem effectively?

VS 2022 Problem with MemoryStream working on second attempt

0
0
Greetings

I'm having trouble using a MemoryStream to display an image bytearray to a picturebox. It works well the first time, but all subsequent attempts throw an exception "Parameter is not valid" with no further information.

Code:

Public Class Form_Main

    Private PreviewArray() As Byte
.
.
    Private Function PreviewImage() As Boolean
.
            ReDim PreviewArray(PreviewLength)

            ' The PreviewArray is then loaded with image byte data
            ' from another source within the application. This works fine.

            ' This line throws an error on second attempt
            Form_ImagePreview.Pic_Preview.Image = ByteToImage(PreviewArray)

    End Function

    Private Function ByteToImage(byteArray As Byte()) As Image

        Dim ms As New MemoryStream(byteArray)
        Dim returnImage As Image = Image.FromStream(ms)
        Return returnImage
        ms.Dispose()

    End Function

End Class



Public Class Form_ImagePreview

    Private Sub Btn_ImgPreviewClose_Click(sender As Object, e As EventArgs) Handles Btn_ImgPreviewClose.Click

        Pic_Preview.Image = Nothing
        Me.Close()

    End Sub


End Class


I've tried all variety of code to declare and dispose of the bytearray and the memorystream with no success.

If you have any suggestions on how to resolve this problem, it would be greatly appreciated.





Latest Images