Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all 28404 articles
Browse latest View live

Retrieving the correct Identity number during an Add and cascade to child dataadapter

$
0
0
Been trying to modify a code bank submission by jmc which shows how to do a parent/child form with autonumbers using Access database. I'm using a Sql Server mdf database.
https://www.vbforums.com/showthread....ert&highlight=

The problem is, if I delete the last parent record from the database (say the ID was 61, so in the datatable the last ID is 60). The next time I do an ADD, the parent ID will show as 61 in the datagridview and when I ADD a child the parent ID cascades to the child just fine. But when I do a SAVE, the parent ID is reset to 62 (or some other higher number depending on how many have been deleted) in the parent table and that change is not cascaded to the child table, the child record parent ID will remain 61. Which causes constraint problems

I've tried retrieving the the Scope_Identity during the insert and also tried during the dataadapter rowupdate. Also tried manually setting up the Autoincrement.

I thought that with Sql Server the Next Identity would be retrieved automatically. It does retrieve a number but not the correct one.

I know this is a lot of code. I hope what I'm doing wrong or not doing will be obvious and you wont have to go through all the code.


Code:

Imports System.Data.SqlClient

Public Class Form4

#Region " Fields "

    ''' <summary>
    ''' Contains the tables and the relation between them.
    ''' </summary>
    Private data As New DataSet

    ''' <summary>
    ''' Connects to the database.
    ''' </summary>
    Private connection As New SqlConnection(My.Settings.BooksDBConnectionString)

    ''' <summary>
    ''' Retrieve data from the database and save changes back to the database.
    ''' </summary>
    ''' <remarks>
    ''' The WithEvents keyword is required so that the adapters can be included in the Handles clause of their RowUpdated event handlers.
    ''' </remarks>
    Private WithEvents parentDataAdapter As New SqlDataAdapter("SELECT BookId, bookName From Books",
                                                                connection) With {.MissingSchemaAction = MissingSchemaAction.AddWithKey}
    Private WithEvents childDataAdapter As New SqlDataAdapter("SELECT ReserveId, BookId, ReserveName From Reserve",
                                                                connection) With {.MissingSchemaAction = MissingSchemaAction.AddWithKey}

    ''' <summary>
    ''' Generate the InsertCommand, UpdateCommand and DeleteCommand for the adapters when their Update method is called.
    ''' </summary>
    Private parentCommandBuilder As New sqlCommandBuilder(Me.parentDataAdapter) With {.QuotePrefix = "[",
                                                                                        .QuoteSuffix = "]"}
    Private childCommandBuilder As New sqlCommandBuilder(Me.childDataAdapter) With {.QuotePrefix = "[",
                                                                                      .QuoteSuffix = "]"}

#End Region 'Fields

#Region " Event Handlers "

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try
            LoadSchema()
            ConfigureAutoIncrements()
            ConfigureRelation()
            LoadData()
            BindData()

            'parentDataAdapter.InsertCommand = parentCommandBuilder.GetInsertCommand()
            'parentDataAdapter.InsertCommand.CommandText += "; Select Scope_Identity()"

        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "Error")
        End Try
    End Sub

    Private Sub parentDataAdapter_RowUpdated(sender As Object, e As SqlRowUpdatedEventArgs) Handles parentDataAdapter.RowUpdated
        'We are only interested in new records.
        'If e.StatementType = StatementType.Insert Then
        '    'Get the last ID auto-generated by the database.
        '    Using command As New SqlCommand("SELECT SCOPE_IDENTITY()", Me.connection)
        '        'Update the ID of the local row.
        '        e.Row("BookID") = CInt(command.ExecuteScalar())
        '    End Using
        'End If
    End Sub

    ''' <summary>
    ''' Raised after a child row is saved to the database.
    ''' </summary>
    ''' <param name="sender">
    ''' The adapter that saved the row.
    ''' </param>
    ''' <param name="e">
    ''' The data for the event.
    ''' </param>
    ''' <remarks>
    ''' This event handler is used to retrieve an auto-generated ID from the database after a row is inserted and update the corresponding row in the local data set.
    ''' </remarks>
    Private Sub childDataAdapter_RowUpdated(sender As Object, e As SqlRowUpdatedEventArgs) Handles childDataAdapter.RowUpdated
        'We are only interested in new records.
        'If e.StatementType = StatementType.Insert Then
        '    Get the last ID auto-generated by the database.
        '    'Using command As New SqlCommand("SELECT @IDENTITY", Me.connection)
        '        Using command As New SqlCommand("SELECT SCOPE_IDENTITY()", Me.connection)
        '            Update the ID of the local row.
        '        e.Row("ReserveID") = CInt(command.ExecuteScalar())
        '        End Using
        'End If
    End Sub
    ''' <summary>
    ''' Raised when the user clicks the Save button on the parent tool bar.
    ''' </summary>
    ''' <param name="sender">
    ''' The Save button.
    ''' </param>
    ''' <param name="e">
    ''' The data for the event.
    ''' </param>
    ''' <remarks>
    ''' Saves all parent and child data.
    ''' </remarks>
    Private Sub SaveToolStripButton_Click(sender As System.Object, e As System.EventArgs) Handles SaveToolStripButton.Click
        If Me.Validate() Then
            Me.parentBindingSource.EndEdit()
            Me.childBindingSource.EndEdit()

            Me.parentDataAdapter.Update(Me.data, "Books")
            Me.childDataAdapter.Update(Me.data, "Reserve")
        End If
    End Sub

#End Region 'Event Handlers

#Region " Methods "

    ''' <summary>
    ''' Build the data set schema without actually retrieving any data.
    ''' </summary>
    Private Sub LoadSchema()
        Me.parentDataAdapter.FillSchema(Me.data, SchemaType.Source, "Books")
        Me.childDataAdapter.FillSchema(Me.data, SchemaType.Source, "Reserve")
    End Sub

    ''' <summary>
    ''' Configure the auto-increment properties of the ID columns of both tables.
    ''' </summary>
    Private Sub ConfigureAutoIncrements()
        ConfigureAutoIncrement(Me.data.Tables("Books").Columns("BookID"))
        ConfigureAutoIncrement(Me.data.Tables("Reserve").Columns("ReserveID"))
    End Sub


    ''' <summary>
    ''' Configure the auto-increment properties of a column.
    ''' </summary>
    ''' <remarks>
    ''' The column will be configured to generate local IDs that will never class with those generated by the database.
    ''' Database IDs will start at 1 and increase sequentially while local IDs will start at 0 and decrease sequentially.
    ''' </remarks>
    Private Sub ConfigureAutoIncrement(column As DataColumn)
        'With column
        '    'The column should automatically generate local IDs.
        '    .AutoIncrement = True

        '    'The first local ID value generated should be 0.
        '    'The database IDs will start at 1, so local IDs will not clash.
        '    .AutoIncrementSeed = 0

        '    'The local IDs should each be 1 less than the previous.
        '    'The database IDs will each be 1 more than the previous, so local IDs will not clash.
        '    .AutoIncrementStep = -1
        'End With
    End Sub
    ''' <summary>
    ''' Configure the foreign key relation between the ParentID columns in the Parent and Child tables.
    ''' </summary>
    ''' <remarks>
    ''' The relation is set to cascade updates, which means that when the local ID in a parent
    ''' row is replaced with the database ID, all related child rows will be updated as well.
    ''' </remarks>
    Private Sub ConfigureRelation()
        Me.data.Relations.Add("ParentChild",
                              Me.data.Tables("Books").Columns("BookID"),
                              Me.data.Tables("Reserve").Columns("BookID"),
                              True).ChildKeyConstraint.UpdateRule = Rule.Cascade
    End Sub

    ''' <summary>
    ''' Retrieve the data from the database.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadData()
        Me.parentDataAdapter.Fill(Me.data, "Books")
        Me.childDataAdapter.Fill(Me.data, "Reserve")
    End Sub

    ''' <summary>
    ''' Displays the data in the grids.
    ''' </summary>
    ''' <remarks>
    ''' The child grid is bound such that it will only display the records related to the selected parent record.
    ''' </remarks>
    Private Sub BindData()
        Me.parentBindingSource.DataSource = Me.data.Tables("Books")
        Me.childBindingSource.DataMember = "ParentChild"
        Me.childBindingSource.DataSource = Me.parentBindingSource

        Me.parentDataGridView.DataSource = Me.parentBindingSource
        Me.childDataGridView.DataSource = Me.childBindingSource
    End Sub

#End Region 'Methods

End Class

Just in case here is the table definition
Code:

CREATE TABLE [dbo].[Books] (
    [BookId]  INT          IDENTITY (1, 1) NOT NULL,
    [BookName] VARCHAR (50) NULL,
    [Author]  VARCHAR (50) NULL,
    [Copies]  INT          NULL,
    PRIMARY KEY CLUSTERED ([BookId] ASC)
);


VS 2012 Bitmap.Save - how do I overcome an InteropServices.ExternalException error?

$
0
0
Following is a very simple program, extracted from my 'real' program. that demonstrates the problem. (For those interested, the jpg file is of dimension 200x200 - any jpg will work.) When I run the program within Visual Studio it works just fine. However, when I run the program stand-alone, I get an InteropServices.ExternalException error. I have searched on this and have tried a variety of things, but I keep getting the error.

Here is the 'entire' program:
Code:

Imports System.Drawing.Imaging

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim imgLI As Image
        imgLI = New Bitmap(Image.FromFile("C:\Users\Gerry\Desktop\SmileFace.jpg"), 150, 150)

        Dim bmp As New Bitmap(250, 250)
        Using bmp
            Dim gr As Graphics = Graphics.FromImage(bmp)
            gr.Clear(Color.WhiteSmoke)
            gr.DrawImage(imgLI, 25, 25)

            bmp.Save("C:\Users\Gerry\Desktop\foobar.jpg", ImageFormat.Jpeg)
            gr.Dispose() ' this line before or after the above does not matter
        End Using
        Application.Exit()
        End
    End Sub
End Class

Please modify this program such that it works as stand-alone. Many thanks.

VS 2010 [RESOLVED] there is no end if why

$
0
0
Code:

Public Function getkeystate(ByVal key1 As Integer) As Boolean
        Dim s As Short
        s = getasynckeystate(key1)
        If s = 0 Then Return False
        Return True
    End Function

why is there no error for the missing end if? why is there no else statement?
Thanks
George

VS 2019 [RESOLVED] Upgrading Framework 4.8 to 5.0 -- x64 or x86 version?

$
0
0
I would like to upgrade from the Framework 4.8 to 5.0 and would like to know how to find out which platform I should download (32-bit or 64-bit).

I have a Windows 10 Pro O/S (64-bit). I am running Visual Studio Community 2019 version 16.9.4.

I thought this information would be shown in the Help menu ("About Visual Studio") but the Framework platform is not included there.

VS 2019 Vb.net Discover selected focus item keydown

$
0
0
I want to get the focus of the objects inside a form and know if they are of type text or if they are of type text, like richtextbox,textbox,wordwrap I can control an event in them created by code, because I will do 5 per code to control but I intend to do it but then I made the following code:

Code:

' captures all form events
For Each formcontrols As Control In Me.Controls
  If formcontrols.HasChildren then
  ''''MsgBox(formcontrols.Controls.Count, MsgboxStyle.OkOnly,"Count Element intro")

'captures whatever textbox there are and finds which one has the focus
For Each textboxbycode As TextBox In Me.Controls
    If textboxbycode.focus then
      ' here the idea is to capture the keydown event
    End if
End If
Next

The code above counts the elements that are inside a form to be unlimited the items now I need to capture the keydown event of these elements without being created is it possible or create a keydown event for it?

[RESOLVED] Weird error right after the db server goes up after being down.

$
0
0
Hi,

So I have a TableAdapter (created by the designer) that fills a table like this.

Code:

Try
        cmd.Connection.Open()
        MyTableAdapter.Fill(MyDataSet.MyTable)
        cmd.Connection.Close()
Catch ex As Exception
        cmd.Connection.Close()
        Throw
End Try


When the db server is up it works fine.
When the db server is down it gives out this error:

MySqlException was caught:
Unable to connect to any of the specified MySQL hosts.


Which is fine too as it's expected.

The problem is when the server goes down and the above error gets thrown and then the server goes up again. When the code gets executed then it gives out this error:

MySqlException was caught:
Fatal error encountered during command execution.


This error happens only the first time the code executed right after the server goes up. When it gets executed the second time (and all the times that follow) it works fine. Which is wired.

Any enlightenment would be very appreciated.

Visual Studio Keep Crashing After Installing A Software

$
0
0
Hi all. :wave:
My installed version of VS is 2012 and that was working satisfactorily until I installed PACTware 5.0 software which it automatically installed a .NET framework as I am aware.

Visual studio startup and homepage opens properly and follow actions but: 1) when I open recent projects "Stopped working" will pop up. 2) When I want to create a new Windows Form Application project a critical error "No exports were found that match constraint: ContractName | Microsoft.VisualStudio.Text.ITextDocumentFactoryService RequiredTypeIdentity | Microsoft.VisualStudio.Text.ITextDocumentFactoryService" will pop up and not continuing.

Is there any possible way without uninstalling/reinstalling PACTware and/or VS?
Thanks in advance.

[RESOLVED] Month calendar

$
0
0
I am trying to use a third party month calendar to jazz up my month calendar.
I have managed to make certain dates based on a a mysql data tabl bold using the standard month calendar control. However I would like to add an image to those dates. Seems like it cannot be done with the standard control.

I have added the .dll van the following https://www.codeproject.com/Articles...0/Calendar-NET

However I cannot see the control in my toolbox. I have tried both the .dll in the binaries and source code download.
I have searched but cannot find a solution.

I am using Visual Studio Community 2019 and .Net 3.0 Core.

Regards

[RESOLVED] Visual Studio Keep Crashing After Installing A Software

$
0
0
Hi all. :wave:
My installed version of VS is 2012 and that was working satisfactorily until I installed PACTware 5.0 software which it automatically installed a .NET framework as I am aware.

Visual studio startup and homepage opens properly and follow actions but: 1) when I open recent projects "Stopped working" will pop up. 2) When I want to create a new Windows Form Application project a critical error "No exports were found that match constraint: ContractName | Microsoft.VisualStudio.Text.ITextDocumentFactoryService RequiredTypeIdentity | Microsoft.VisualStudio.Text.ITextDocumentFactoryService" will pop up and not continuing.

Is there any possible way without uninstalling/reinstalling PACTware and/or VS?
Thanks in advance.

VS 2008 Getting Data from a Json array

$
0
0
Hi Everyone,

I hope someone can explain something for me

I have the following JSON data that is sent from my supplier


Code:

{
  "balances": {
    "currency": "GBP",
    "issuerTotals": {},
    "totalAmount": 0,
    "totalRefundsAmount": 0,
    "totalRefundsCount": 0,
    "totalSalesAmount": 0,
    "totalSalesCount": 0,
    "totalCashbackAmount": 0,
    "totalCashbackCount": 0,
    "totalGratuityAmount": 0,
    "totalGratuityCount": 0,
    "totalsSince": "15/07/21 17:10",
    "waiterTotals": {}
  },
  "banking": {
    "Cardnet MS": {
      "currency": "",
      "currentSessionIssuerTotals": {},
      "previousSessionIssuerTotals": {},
      "currentSessionTotals": {
        "currency": "",
        "totalAmount": 0,
        "totalRefundsAmount": 0,
        "totalRefundsCount": 0,
        "totalSalesAmount": 0,
        "totalSalesCount": 0
      },
      "previousSessionTotals": {
        "currency": "",
        "totalAmount": 0,
        "totalRefundsAmount": 0,
        "totalRefundsCount": 0,
        "totalSalesAmount": 0,
        "totalSalesCount": 0
      },
      "currentSessionTransactionNumbers": [
        "",
        ""
      ],
      "previousSessionTransactionNumbers": [
        "",
        ""
      ]
    }
  },
  "reportLines": [
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "END OF DAY"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "Z BALANCES"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "Totals reset"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "Thank you"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "15/07/21 17:17"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "HANDSET:01"
    },
    {
      "format": [],
      "type": "LINE_SEPARATOR_DOUBLE",
      "value": "========"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "GRAND TOTALS"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "Since 15/07/21 17:10"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_HEIGHT"
      ],
      "type": "TEXT",
      "value": "No Business"
    },
    {
      "format": [],
      "type": "LINE_SEPARATOR_DOUBLE",
      "value": "========"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "REPORT COMPLETE"
    },
    {
      "format": [],
      "type": "TICKET_FEED",
      "value": "\n\n\n\n\n"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "END OF DAY"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "BANKING    "
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "  "
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_HEIGHT"
      ],
      "type": "TEXT",
      "value": "Algpos                  "
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_HEIGHT"
      ],
      "type": "TEXT",
      "value": "NN4 6EP"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "Thank you"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "TID:22165264"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "15/07/21 17:17"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "HANDSET:01"
    },
    {
      "format": [],
      "type": "LINE_SEPARATOR_DOUBLE",
      "value": "========"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "Cardnet MS"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "TOTALS CONFIRMED"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "15/07/21 17:17"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "CURRENT SESSION:      0"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_HEIGHT"
      ],
      "type": "TEXT",
      "value": "No Business"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "PREVIOUS SESSION:"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "No Business"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "TXN 0094"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "COMPLETED"
    },
    {
      "format": [],
      "type": "TEXT",
      "value": "DIAG 3576"
    },
    {
      "format": [],
      "type": "LINE_SEPARATOR_DOUBLE",
      "value": "========"
    },
    {
      "format": [
        "BOLD",
        "DOUBLE_WIDTH"
      ],
      "type": "TEXT",
      "value": "REPORT COMPLETE"
    }
  ],
  "reportTime": "2021-07-15T17:17:00",
  "reportType": "END_OF_DAY",
  "reportResult": "COMPLETED",
  "notifications": [
    "REPORT_FINISHED",
    "REPORT_STARTED"
  ],
  "userMessage": ""
}

What I would like explained please is how do I get the data from the sub Functions. (when I mean sub functions i mean for example

Code:

"notifications": [
    "REPORT_FINISHED",
    "REPORT_STARTED"
  ]

or everything that is under the "reportLines" header

I would apreachate any advice anyone can give me

Changing a field length and its values in VB.NET

$
0
0
Hi all. :wave:
Consider a field of variables like below:
Code:

    Private Sendcmd() As Byte

    Public Sub New()
        InitializeComponent()
    End Sub

There is a NumericUpDown control (called SendLenght) which determines Sendcmd length i.e. from 1 to 64.
By clicking a button, filling Sendcmd with NumericUpDown values from 1 to current value of SendLenght. (There are 64 NumericUpDown maximum)

How can I do such thing in VB.NET?
I tried for loop as shown below but I suspected an array or collection making is required.
Code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim NumericUpDown As NumericUpDown() = {NumericUpDown1, NumericUpDown2, NumericUpDown3, NumericUpDown4, NumericUpDown5, NumericUpDown6, NumericUpDown7, NumericUpDown8, NumericUpDown9, NumericUpDown10, NumericUpDown11, NumericUpDown12, NumericUpDown13, NumericUpDown14, NumericUpDown15, NumericUpDown16, NumericUpDown17, NumericUpDown18, NumericUpDown19, NumericUpDown20, NumericUpDown21, NumericUpDown22, NumericUpDown23, NumericUpDown24, NumericUpDown25, NumericUpDown26, NumericUpDown27, NumericUpDown28, NumericUpDown29, NumericUpDown30, NumericUpDown31, NumericUpDown32, NumericUpDown33, NumericUpDown34, NumericUpDown35, NumericUpDown36, NumericUpDown37, NumericUpDown38, NumericUpDown39, NumericUpDown40, NumericUpDown41, NumericUpDown42, NumericUpDown43, NumericUpDown44, NumericUpDown45, NumericUpDown46, NumericUpDown47, NumericUpDown48, NumericUpDown49, NumericUpDown50, NumericUpDown51, NumericUpDown52, NumericUpDown53, NumericUpDown54, NumericUpDown55, NumericUpDown56, NumericUpDown57, NumericUpDown58, NumericUpDown59, NumericUpDown60, NumericUpDown61, NumericUpDown62, NumericUpDown63, NumericUpDown64}
        For i As Decimal = 1 To SendLenght.Value
            Sendcmd(i - 1)=Sendcmd(i - 1) {NumericUpDown i - 1}  '<-- End of statement expected error to this line
        Next
    End Sub

Thanks in advanced.

______________________________________________
/UPDATE/
Expected results:

For SendLenght.Value = 1
Code:

Sendcmd(1) = {NumericUpDown1.Value}
For SendLenght.Value = 2
Code:

Sendcmd(2) = {NumericUpDown1.Value, NumericUpDown2.Value}
For SendLenght.Value = 10
Code:

Sendcmd(10) = {NumericUpDown1.Value, NumericUpDown2.Value, NumericUpDown3.Value, NumericUpDown4.Value, NumericUpDown5.Value, NumericUpDown6.Value, NumericUpDown7.Value, NumericUpDown8.Value, NumericUpDown9.Value, NumericUpDown10.Value}

[RESOLVED] Excel formula to VB.NET

$
0
0
Hi

I have an Excel sheet that I want to transfer to a standalone application.

The goal of the sheet is to determine which groups on the server we need to merge to ensure that there are sufficient storage for each department. Preferably, we do not want departments to have to log in to different systems to view their data.

My approach in VB.net
1. Create a dynamic array to ensure all data parameters can be added.
2. Add group sizes to array index using a for loop
3. Assigning the groups to each department (where I am currently stuck) - More than one department can be on the same group. If a department's data requirement is too large for the current group size, it must say 'Invalid' -> more of an indication that we need to merge groups for this department.

I have attached a snip from my Excel file to indicate the desired output.

Name:  Excel sheet snip.png
Views: 49
Size:  12.9 KB

Hope this makes sense and thank you in advance for your help.
Attached Images
 

VS 2010 position cursor

$
0
0
Hello
I've been trying to locate cursor at a given position on my form. googling has not helped so far.
if you could point me in the right direction or provide a code example I would be grateful.
george

SerialPort Low Level Settings?

$
0
0
Hi all. :wave:

Mimicking a RS-232 communication with a specific device is desired.
General settings (Baud rate, Parity, Handshake, Word length and other properties grid provided) were done and confirmed that they're OK. A correct sequence of request command was applied through the port but no answers were received.

After monitoring what's happening on the port, found that some settings were different in spite of "general" (some-say) settings are matched. Different subitems are as following:

Code:

---------------
Eofchar              0
Errorchar            0
Breakchar            0
Eventchar            0
Xonchar              17
Xoffchar              19
---------------
Flags=0x0000000F
---------------
ControlHandshake      0x01
Flowreplace          0x00
Xonlimit              100
Xofflimit            100
---------------

The question is how to access and change their values to desirable values?
Is it even possible? Should I renew my V.S.? I gathered some articles in different forums (even here) but nothing operational were catch.
All mentioned parameters are not members of 'System.IO.Ports.SerialPort'. Maybe you could introduce me a way to achieve a kind of low level accessibility.
Thanks in advance.

VS 2019 [RESOLVED] Need help deleting a record

$
0
0
I cannot figure out why my code is failing when I attempt to delete a row. Here's the code:

Code:

If dsMain.Tables("Fuel").GetChanges IsNot Nothing Then
    iAdd = dsMain.Tables("Fuel").Select(vbNullString, vbNullString, DataViewRowState.Added).Length
    iDel = dsMain.Tables("Fuel").Select(vbNullString, vbNullString, DataViewRowState.Deleted).Length
    iMod = dsMain.Tables("Fuel").Select(vbNullString, vbNullString, DataViewRowState.ModifiedCurrent).Length
    Try
        i = daFuel.Update(dsMain.Tables("Fuel")) '...AcceptChanges is explicitly called
        myTimer.Stop()
        strMSG = "Operation complete, " & i & CStr(IIf(i = 1, " row", " rows")) & " saved (" & TickString(myTimer.ElapsedTicks) & "):" & vbCrLf &
            Space(4) & Chr(149) & " Added = " & iAdd & vbCrLf &
            Space(4) & Chr(149) & " Deleted = " & iDel & vbCrLf &
            Space(4) & Chr(149) & " Modified = " & iMod
        MessageBox.Show(strMSG, "Save Data", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Catch ex As Exception
        strMSG = "Error message:" & vbCrLf & ex.Message & vbCrLf & vbCrLf & "StackTrace:" & vbCrLf & ex.StackTrace
        MessageBox.Show(strMSG, "Save Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End If

I can see via the Immediate Window that the value of iDel is 1, but the "daFuel.Update(dsMain.Tables("Fuel"))" statement raises an error.

Here's the error message:

Name:  2021-07-18_8-05-30.jpg
Views: 23
Size:  64.7 KB

Here is the daFuel.DeleteCommand:

Code:

Dim deleteData As New SQLite.SQLiteCommand("DELETE * FROM [Fuel] WHERE RecID = @RecID", con)
deleteData.Parameters.Add("@RecID", DbType.Int32).SourceColumn = "RecID"
daFuel.DeleteCommand = deleteData

Any assistance on this will be greatly appreciated!
Attached Images
 

VS 2010 NAudio installation help

$
0
0
Hi,

Someone can help with installation of NAudio library?
I added reference to naudio.dll then Imports Naudio.Wave and have errors.
I found few threads on this forum about naudio but without satisfied answer.
In soultion explorer naudio is visible

VS 2019 Prepending text to multiple lines in i .txt file (vb.net 2019)

$
0
0
Hello. I have a .txt file with around 120,000 lines forming a series of matrices or arrays (I thought it was much more, but thankfully is only this). Each line looks a bit like this:
-2.986489e+006, 4.7354682e+008, 2.64839292e+007, -1.647282922e+004, 4.846473829e+007
Each line has 5 values, like above. I would like to prepend the text to put in a piece of string and a linear progression of numbers at the beginning of each line, so it would go "(string) 1, (string) 2, (string) 3," one each at the beginning of each line.

The initial file did not have delimiters in between each value, so I wrote a piece of code to put a "," at the end of each value. The code looks like this:

Code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim filename As String = "C:\New Folder\Programming\Residual Stressl.txt"
        Dim endrs As String
        endrs = TextBox2.Text
        Dim endrs2 As String
        endrs2 = TextBox3.Text
        Dim x As Double = 0
        Dim fcontent As String()
        fcontent = IO.File.ReadAllLines(filename)

        For Each field As String In fcontent
            If field.Contains(endrs) Then
                fcontent(x) = fcontent(x).Replace(endrs, endrs2)
            End If
            x += 1
        Next
        IO.File.WriteAllLines(filename, fcontent)
    End Sub

I could do this because every value ends in 004, 005, 006, 007 or 008. However, I am having trouble finding a way to prepend each line. There is the function ".endswith" but I am not sure how to use that to prepend, or indeed, if it would write at the beginning of the line or at the beginning of each value. To make it more difficult, I also need to skip every second line as every second line contains just two numbers which I need to keep as they are relevant to the data, but aren't part of the array.
I've been reading up on the Microsoft website and researching for days now, and can't find the information I need to do this. There is plenty on writing to a new file, or appending, or prepending to a piece of string in the program, but little on prepending to an existing file. Please, could anyone give me a pointer in the right direction? Thank you :)

VS 2015 working with multiple worksheets in an EXCEL workbook at one time

$
0
0
My VB.NET code creates an EXCEL workbook and adds 5 worksheets. I would to apply some formatting to all 5 worksheets at one time instead of applying the formatting to each sheet separately.

For example, abbreviated
wrkbk.Sheets("Sheet1").Font.Bold = True
wrkbk.Sheets("Sheet2").Font.Bold = True
wrkbk.Sheets("Sheet3").Font.Bold = True
wrkbk.Sheets("Sheet4").Font.Bold = True
wrkbk.Sheets("Sheet5").Font.Bold = True

I would like to do something like the below as a one liner instead of five separate lines, as above
wrkbk.Sheets("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5").Font.Bold = True

I have a lot for formatting to do to each sheet. The above is just one example of the formatting that needs to be applied to each sheet.

If someone knows how to do this then a reply would be appreciated.

TIA
Bill

VS 2010 [RESOLVED] NAudio installation help

$
0
0
Hi,

Someone can help with installation of NAudio library?
I added reference to naudio.dll then Imports Naudio.Wave and have errors.
I found few threads on this forum about naudio but without satisfied answer.
In soultion explorer naudio is visible

VS 2019 [RESOLVED] Prepending text to multiple lines in i .txt file (vb.net 2019)

$
0
0
Hello. I have a .txt file with around 120,000 lines forming a series of matrices or arrays (I thought it was much more, but thankfully is only this). Each line looks a bit like this:
-2.986489e+006, 4.7354682e+008, 2.64839292e+007, -1.647282922e+004, 4.846473829e+007
Each line has 5 values, like above. I would like to prepend the text to put in a piece of string and a linear progression of numbers at the beginning of each line, so it would go "(string) 1, (string) 2, (string) 3," one each at the beginning of each line.

The initial file did not have delimiters in between each value, so I wrote a piece of code to put a "," at the end of each value. The code looks like this:

Code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim filename As String = "C:\New Folder\Programming\Residual Stressl.txt"
        Dim endrs As String
        endrs = TextBox2.Text
        Dim endrs2 As String
        endrs2 = TextBox3.Text
        Dim x As Double = 0
        Dim fcontent As String()
        fcontent = IO.File.ReadAllLines(filename)

        For Each field As String In fcontent
            If field.Contains(endrs) Then
                fcontent(x) = fcontent(x).Replace(endrs, endrs2)
            End If
            x += 1
        Next
        IO.File.WriteAllLines(filename, fcontent)
    End Sub

I could do this because every value ends in 004, 005, 006, 007 or 008. However, I am having trouble finding a way to prepend each line. There is the function ".endswith" but I am not sure how to use that to prepend, or indeed, if it would write at the beginning of the line or at the beginning of each value. To make it more difficult, I also need to skip every second line as every second line contains just two numbers which I need to keep as they are relevant to the data, but aren't part of the array.
I've been reading up on the Microsoft website and researching for days now, and can't find the information I need to do this. There is plenty on writing to a new file, or appending, or prepending to a piece of string in the program, but little on prepending to an existing file. Please, could anyone give me a pointer in the right direction? Thank you :)
Viewing all 28404 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>