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

VS 2017 [RESOLVED] Pass a Control's Name to a Sub

$
0
0
I was wondering if the was a way to pass a control's name to a Sub. I have looked, cannot find anything that works. I have tested various scenarios but cannot get anything to work. Maybe I do not know what I am looking at.

I have several DGV's that have common code. So instead of coding each one differently I would life to pass the name, in this case the DGV design name, dgvSolarSystem.

would like to pass that to the Sub.

Code:

      Me.dgvSolarSystem.EnableHeadersVisualStyles = False
        With Me.dgvSolarSystem.ColumnHeadersDefaultCellStyle
            '.Font = New Font(dgvSolarSystem.Font, FontStyle.Bold)
            .BackColor = Color.Gainsboro
            .Alignment = DataGridViewContentAlignment.MiddleCenter
        End With


        'Format DGV Rows = Aternate Colors
        Dim objAlternatingCellStyle As New DataGridViewCellStyle() With {.BackColor = Color.WhiteSmoke}

                Me.dgvSolarSystem.AlternatingRowsDefaultCellStyle = objAlternatingCellStyle


VS 2015 What is the correct way to Hash a File - Stream reader or Byte Array

$
0
0
Hello all,

I am trying to determine the Most accurate way to generate a Hash for a given file.

When I read a file like this, it takes a few seconds to read and it generates a Hash

Code:

                        Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
                        Dim f As FileStream = New FileStream(foundFile, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, useAsync:=True)
                        md5.ComputeHash(f)
                        f.Close()

When I read a file like this, it's almost instantaneous and it generates a different Hash.

Code:

                        Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
                        Dim tmpSource() As Byte = ASCIIEncoding.ASCII.GetBytes(foundFile)
                        md5.ComputeHash(tmpSource)

I need to know what is the most accurate way to compare multiple files for duplication and ensure it remains unchanged as time passes. Obviously I would prefer the faster method but the speed at which I processed 200GB of data using the Byte Array and the fact that it creates a different Hash String from an actual read, leads me to doubt it accuracy.

Does anyone know the difference between the two methods (related to Hashing) and why one would be chosen over another?

Thanks,

-NJ

VS 2010 Need to change where links in Excel workbooks point

$
0
0
Using VB.NET 2010, the company I work for has a folder with a large number (hundreds) of Excel workbooks that correspond to models of products. Each workbook contains descriptions with multiple links that point to drawings on our network. We need to move the drawings but all of these links were generated independently over many years, so there is no central pointer I can change to make all the links point to the new location. I'm not really involved in this, but was just thinking about a way this could be fixed. If I can find a solution, I may volunteer it. Anyway, I have written code with VB.NET that allows me to interact with Excel, by launching a workbook and populating it with various values, saving, printing, etc. I have never messed with links. My questions are...
1. How would I go about gathering up all the links to change them? I picture a program that will gather up the workbooks, as I would do getting files in a directory, and step through them using a "for each" type command. There may or may not be multiple sheets in a given workbook. When running the code, it would go through, one by one, each workbook, open it, gather a list of the links on all sheets and change them all to point to the new destination, then save the workbook and move onto the next workbook.
2. Is there a way to, without going through each and every workbook, to make the links in these workbooks get their destination from a central location, such as a file in the same folder, or similar? I realize this is an Excel/VBA question and not a VB.NET question.
Thanks.

VS 2017 Create and Open a Blank xml Data File from a Bound DataSet

$
0
0
I have an application, when user first opens it, there is no data or xml data file. I have a bound data set with various tables. One of the tables will hold the project information. Namely, the project name, description, site. As well as the data file location and name.

So when there is no data file, the application will prompt the user to either open an existing file or create a new one. If the user selects Create a new Project, application will prompt for a file location and a new file name. Once this is done they can add the project information such as project name, description, etc. Once this is done the user can proceed with the other project tasks which will be saved in the file. If the user opens an existing file, the data will be loaded into the application.

I have no problem with the file dialogs, reading and writing of the data file. I have no idea how to create a new xml data file from the configured data set.

VS 2017 Link RTD

$
0
0
Boa noite, ou bom dia.
Possuo um Link RTD contratado, que é um plugin Excel. Para acessá-lo preciso abrir uma planilha em Excel, e aí ele me pede
usuário e senha. Feito isso o link passa a transmitir os dados, mas para a planilha.

Existe a possibilidade se logar diretamente e ler os dados recebidos do Link, sem ter que abrir uma planilha para tal?

Meu objetivo é transferir esses dados para um datagridview. Estou utilizando VB Net 2017.

Desde já agradeço a atenção dispensada.

Abraços
Dalton Serkez

[RESOLVED] Strict paradoxon

$
0
0
we all know that "strict on" is usually more picky than "strict off". it Shows Errors whenever an implicit cast would be required.
i now came accross a weird issue where strict on does not Show any error but strict off does!
the error is "overload Resolution failed" and this is the code:

Code:

Option Strict On

Public Class Form1

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        e.Graphics.DrawEllipse(Pens.Black, 0.5, 0.5, 100, 100)
    End Sub

End Class

it compiles well as is, but if you Change to strict off, it Shows the error.
while i have got my own theory involving the Interpretation of the literals "0.5" and "1" during compilation i would really like to learn what you guys think that the Problem is. Or maybe someone really knows for sure?

tested under 2010 Prof.

cheers

[RESOLVED] How to check if a number is whole or a decimal?

$
0
0
I know this is a 5th-grade question, but is there a function in VB.Net that can determine whether is a calculated value is a whole number or a decimal?

VS 2012 [RESOLVED] What is the best way to close all open child forms

$
0
0
Hello, I need some help.

How (what is the best way) to close all open child forms in VB.NET?

Here is my code and screenshot of the program.

Name:  Screenshot_1.jpg
Views: 81
Size:  28.8 KB

vb.net Code:
  1. Public Sub ShowForm(ByVal Frm As Form)
  2.         For Each frmClose As Form In MainForm.MdiChildren
  3.             frmClose.Close()
  4.             frmClose.Dispose()
  5.         Next
  6.         With Frm
  7.             .MdiParent = MainForm
  8.             .Show()
  9.             .WindowState = FormWindowState.Maximized
  10.         End With
  11.     End Sub

vb.net Code:
  1. Private Sub TsbTPR_Click(sender As Object, e As EventArgs) Handles TsbTPR.Click
  2.         ShowForm(FrmPermintaan)
  3.     End Sub

When I click another form, it seems like the "form closing" process is not really neat and see some blink.

Video: https://www.screencast.com/t/M8NYwOVDH

Also, when I use the above code and I click the same form, it gives this error:
Cannot access a disposed object.
Name:  Screenshot_4.jpg
Views: 61
Size:  30.7 KB

Please help
Attached Images
    

VS 2017 [RESOLVED] Will VS 2017 really not run on W7?

$
0
0
I've been using VB.NET 2010 for years now and was finally ready to try out the latest. I just downloaded VS 2017. It installed, but won't let me create a project because my OS is W7. Really? I recently read that half of all the Windows OS's out there are W7. What gives? Do they expect us to write code that only works on W10? Can it be made to run on W7, or do I have to go to VS 2015?

Retrieving index of combobox in datagridview for update to DB

$
0
0
Hello,

Most of my experience in in VB6... I am trying to convert to VB.NET. I have visual studio 2013.

I have a datagridview with multiple comboboxes. The idea if for the user to select values for all combos and then click the "Save" button to update the database.

I am only storing the numeric equivalent which refers to the index. I cannot figure out how to retrieve the index of the selection in each cell. I was thinking somehow I could use ENUM but can't figure out how to use that either.

Attachment 146835

The database field "percent_type" holds a value of 0, 1 or 2 which corresponds to the choices in the drop down list.

I highlighted the code that refers to my problem area.

Code:

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Dim db As New DataAccess.sqlDataBase("hp_accting")
        Dim dbReader As New DataAccess.sqlDataBase("hp_accting")

        Dim xColumn As Integer = 1

        Try
            Do While xColumn < dtgAllocation.ColumnCount()

                For xAllocation As Integer = 0 To 13
                    Dim colcmb As DataGridViewColumn = DirectCast(dtgAllocation.Columns(xColumn), DataGridViewColumn)
                    Dim cmb As DataGridViewComboBoxCell = DirectCast(dtgAllocation.Rows(xAllocation).Cells(xColumn), DataGridViewComboBoxCell)
 
                    Dim readerCheck As SqlClient.SqlDataReader = dbReader.GetRecords("tax_owner_allocations", "*", "allocation_code = " &
                    xAllocation.ToString & " AND ocode ='" & colcmb.Name.Trim.ToString & "' AND entity_num = '" & cmbEntity.Text.Substring(0, 8).Trim &
                    "' AND projection_year = '" & cmbYear.Text & "'")

                    If readerCheck.HasRows Then
                        db.UpdateRecordField("UPDATE tax_owner_allocations SET percent_type = " & cmb.Value & " WHERE allocation_code = " &
                            xAllocation.ToString & " AND ocode ='" & colcmb.Name.Trim.ToString &
                            "' AND entity_num = '" & cmbEntity.Text.Substring(0, 8).Trim.ToString & "' AND projection_year = '" & cmbYear.Text.ToString & "'")
                    Else
                        db.InsertRecord("tax_owner_allocations", "ocode, entity_num, projection_year, allocation_code, percent_type", "'" & colcmb.Name.Trim &
                                        "', '" & cmbEntity.Text.Substring(0, 8).Trim.ToString & "', '" & cmbYear.Text & "'," & xAllocation.ToString & ", " & cmb.RowIndex.ToString)
                    End If

                    readerCheck.Close()
                    colcmb.Dispose()
                    cmb.Dispose()
                    readerCheck = Nothing
                Next

                xColumn += 1

            Loop
            db = Nothing

            MsgBox("Update was successful!", MessageBoxButtons.OK, "Update Complete")

        Catch ex As Exception

            MsgBox("An error occured while updating this record.", MsgBoxStyle.OkOnly, "Update Cancelled")

        End Try

    End Sub

I have scoured the internet and tried many different things... this is my last resort... please help!! :confused:

Thank you in advance.
Chrissy

VS 2010 how insert animated images on Richtextbox?

$
0
0
how insert animated images on Richtextbox?
(i found, on Code Bank, a code but it's for VB6)

[RESOLVED] The system cannot find the file specified - but I can

$
0
0
Hey all,
I'm putting together a method to switch users on a kiosk app and am trying to use this code...
Code:

Const fName = "C:\Windows\System32\tsdiscon.exe"
Process.Start(fName)

When I run that, I get a Win32Exception on the call to Process.Start saying the file cannot be found. If however I copy and paste the file name into a cmd prompt it runs fine. Just for giggles, I tried using Shell, but get similar results.

So if the file is there why is it not there?
Can anyone reproduce it or is it just me?
Maybe a security setting on my machine?

I've tried starting VS2013 with admin rights but it makes no difference.



Please note that if you are going to try this code, you will (should) be disconnected and shown the switch user screen from which you can log right back in.

VS 2017 XML document load error using LoadXml function in code

$
0
0
I am trying to append to an xml file from Visual Studio 2017 using VB.net. When I invoke the LoadXml function Visual Studio throws an "exception unhandled from System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1".

First I see nothing odd with the beginning of the xml file named 'SML_ErrorLog.Xml'. The first line of characters are:
<?xml version="1.0" encoding="UTF-8"?>
<ExceptionLog>
....
</ExceptionLog>


Any help please? I am pulling my hair out.
Thanks in advance.

VS 2017 Error Code: Status: [ object Object] Ex: error

$
0
0
I keep getting the same error no matter what string as output: "Error Code: Status: [ object Object] Ex: error". This exact code worked in c# except the <WebMethod>.


Default.aspx.vb
Code:

  <System.Web.Services.WebMethod> Public Shared Function GetDate(ByVal mo As Integer, ByVal dy As Integer, ByVal yr As Integer) As String
        Dim output As String = "Check"
        Return output
    End Function

Default.aspx
Code:

    <script type="text/javascript" src="~/jquery=1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%= Button1.ClientID %>").click(function () {
                var mo1 = $("#<%= TextBox1.ClientID %>").val();
                var dy1 = $("#<%= TextBox2.ClientID %>").val();
                var yr1 = $("#<%= TextBox3.ClientID %>").val();
                var data = { mo: mo1, dy: dy1, yr: yr1 };
                var json1 = JSON.stringify(data);
                $.ajax
                ({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: json1,
                    url: "Default.aspx/GetDate",
                    success: function (result) {
                        $("#<%= TextBox4.ClientID %>").val(result.d);
                        $("#<%= Button2.ClientID %>").trigger(click);
                    },
                        error: function (status, ex) {
                        alert("Error Code: Status: " + status + " Ex: " + ex);
                    }
                });
                return false;
            });
        });
    </script>

DataGridViewCheckBoxCell checks when hovering over!

$
0
0
I have a Windows DataGridView that has two checkbox columns. The problem I'm having is when I go to check one of the checkboxes, the box becomes checked just before I check it. I don't have a MouseOver Event in my code so I'm wondering what would cause that?

Thanks,

Error message: BC30420

$
0
0
Hi All, I have an error message on frequent basis:

BC30420 'Sub Main' was not found in ConsoleApp1.Module1

even my code is very simple such as

Code:

Module Module1
    Sub Main()

        MsgBox("TEST")

    End Sub

End Module

I have read online, tried to delete the whole code, restarted the new project a few times but the same error keeps popping up. I could not fix myself. PLEASE PLEASE help me out.

Thank you All

VS 2015 How to compare remove duplicate row in cell datagridview visual basic studio 2015

$
0
0
hey,all
i'm new in vb.net
i try some code when i googling about that, but has not succeeded
please anyone help me to find solution for this problem

Name:  img1.jpg
Views: 34
Size:  34.4 KB

if button compare on click in datagridview show unique row cell, duplicate row deleted

and can be saved in file excel

Name:  img2.jpg
Views: 28
Size:  34.4 KB

in this code i used

Code:


Option Explicit On
Imports System.IO
'Imports Microsoft.Office.Interop
'Imports System.Data
Imports System.Data.OleDb

Public Class Form1

    Dim excelLocation As String = "C:\hasiltest.xlsx"
    Dim MyConn As OleDbConnection
    Dim da As OleDbDataAdapter
    Dim ds As DataSet
    Dim tables As DataTableCollection
    Dim source1 As New BindingSource
    Dim APP As New Excel.Application
    Dim worksheet As Excel.Worksheet
    Dim workbook As Excel.Workbook


    Private Sub btnBrowse1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse1.Click
        Dim myFileDlogOri As New OpenFileDialog()
        myFileDlogOri.InitialDirectory = "c:\"
        'specifies what type of data files to look for
        myFileDlogOri.Filter = "All Files (*.*)|*.*" &
            "|Data Files (*.xlsx)|*.xlsx"
        'specifies which data type is focused on start up
        myFileDlogOri.FilterIndex = 2
        'Gets or sets a value indicating whether the dialog box restores the current directory before closing.
        myFileDlogOri.RestoreDirectory = True
        'seperates message outputs for files found or not found
        If myFileDlogOri.ShowDialog() =
            DialogResult.OK Then
            If Dir(myFileDlogOri.FileName) <> "" Then
                'MsgBox("File Exists: " & myFileDlogOri.FileName, MsgBoxStyle.Information)
            Else
                MsgBox("File Not Found", MsgBoxStyle.Critical)
            End If
        End If
        'Adds the file directory to the text box
        txtFile1.Text = myFileDlogOri.FileName
    End Sub

    Private Sub btnBrowse2_Click(sender As Object, e As EventArgs) Handles btnBrowse2.Click
        Dim myFileDlogCam As New OpenFileDialog()
        myFileDlogCam.InitialDirectory = "c:\"
        'specifies what type of data files to look for
        myFileDlogCam.Filter = "All Files (*.*)|*.*" & "|Data Files (*.xlsx)|*.xlsx"
        'specifies which data type is focused on start up
        myFileDlogCam.FilterIndex = 2
        'Gets or sets a value indicating whether the dialog box restores the current directory before closing.
        myFileDlogCam.RestoreDirectory = True
        'seperates message outputs for files found or not found
        If myFileDlogCam.ShowDialog() =
            DialogResult.OK Then
            If Dir(myFileDlogCam.FileName) <> "" Then
                'MsgBox("File Exists: " & myFileDlogCam.FileName, MsgBoxStyle.Information)
            Else
                MsgBox("File Not Found", MsgBoxStyle.Critical)
            End If
        End If
        'Adds the file directory to the text box
        txtFile2.Text = myFileDlogCam.FileName
    End Sub
    Private Sub btnView1_Click(sender As Object, e As EventArgs) Handles btnView1.Click
        Dim exConn As OleDbConnection
        Dim dt As DataSet
        Dim cmd As OleDbDataAdapter
        Dim sConn As String
        'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & "'C:\File1.xlsx';Extended Properties=Excel 12.0;"
        sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & txtFile1.Text & ";Extended Properties=Excel 8.0;"
        'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & txtFileOri.Text & ";Extended Properties=" & cmbExtFile.Text & ";"
        exConn = New System.Data.OleDb.OleDbConnection(sConn)
        cmd = New System.Data.OleDb.OleDbDataAdapter(
              "select * from [Sheet1$]", exConn)
        'cmd.TableMappings.Add("Table1", "Tabel O")
        dt = New System.Data.DataSet
        cmd.Fill(dt)
        dgvFile1.DataSource = dt.Tables(0)
        exConn.Close()
    End Sub

    Private Sub btnView2_Click(sender As Object, e As EventArgs) Handles btnView2.Click
        Dim exConn As OleDbConnection
        Dim dt As DataSet
        Dim cmd As OleDbDataAdapter
        Dim sConn As String
        'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & "'C:\File2.xlsx';Extended Properties=Excel 12.0;"
        sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & txtFile2.Text & ";Extended Properties=Excel 8.0;"
        exConn = New System.Data.OleDb.OleDbConnection(sConn)
        cmd = New System.Data.OleDb.OleDbDataAdapter(
              "select * from [Sheet1$] [Sheet2$]", exConn)
        'cmd.TableMappings.Add("Table2", "Tabel C")
        dt = New System.Data.DataSet
        cmd.Fill(dt)
        dgvFile2.DataSource = dt.Tables(0)
        exConn.Close()
    End Sub
    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        End
    End Sub
    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

        Dim writer As TextWriter = New StreamWriter("C:\report.xls")
        For i As Integer = 0 To dgvCompare.Rows.Count - 2 Step +1
            For j As Integer = 0 To dgvCompare.Columns.Count - 1 Step +1
                writer.Write(dgvCompare.Rows(i).Cells(j).Value.ToString())
            Next
            writer.WriteLine("")
            'writer.WriteLine("---------------------------------------------")
        Next
        writer.Close()
        MessageBox.Show("Data Exported")
    End Sub


End Class


thank you
Attached Images
  

VS 2010 [RESOLVED] Prevent errors when doing a Webrequest?

$
0
0
I know that best way is with Try Catch but..
vb.net Code:
  1. Imports System.IO
  2. Imports System.Net
  3. Public Class Form1
  4.     Dim pos1, pos2 As Long
  5.     Dim US As String
  6.     Dim request As WebRequest = WebRequest.Create("http://www.nbrm.mk/klservicewebclient/ExcRateSmall.aspx?lang=MK")
  7.     Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
  8.     Dim datastream As Stream = response.GetResponseStream
  9.     Dim reader As New StreamReader(datastream)
  10.     Dim strdata As String = reader.ReadToEnd
But the problem is that i can't use there Try Catch Method because code is in Global variables..
I can't put in another place because i need for whole program :)
So can anyone help me how to avoid if WebRequest fail - how to avoid errors..?
I also google for it..

Thanks :)

Is it possible to manually fire event inside an event?

$
0
0
Planning to use the keydown event to fire the dgv click event. Is it possible?

VS 2015 Finding the Most Frequent and Least Frequent Values in an Array

$
0
0
Hey i have some code to a program, but i need to find the most frequent and least frequent numbers from an array. (that were chosen from a combo-box and added to an array) How do i go about this? This is my code.

Code:

Public Class frm1
    Dim arrAisle(100) As String
    Dim intIndex As Integer
    Dim intCurrentElement As Integer
    Dim intCurrentValue As Integer
    Dim intElementFreq As Integer
    Dim intLargestFreq As Integer
    Dim intLeastFreq As Integer
    Dim decTotalCost As Decimal
    Dim decAvgCost As Decimal

    Private Sub frm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For i = 1 To 10
            cboxAisle.Items.Add(i)
        Next
        cboxAisle.DropDownStyle = ComboBoxStyle.DropDownList
    End Sub

    Private Sub btnPurchase_Click(sender As Object, e As EventArgs) Handles btnPurchase.Click
        Try
            AddtoArray()
            intIndex += 1
        Catch ex As IndexOutOfRangeException
            ReDim Preserve arrAisle(intIndex * 2)
            AddtoArray()
            intIndex += 1
        End Try
    End Sub

    Private Sub AddtoArray()
        If txtCost.Text <> "" Then
            arrAisle(intIndex) = txtCost.Text
            arrAisle(intIndex) = cboxAisle.SelectedText
            decTotalCost = decTotalCost + txtCost.Text
            decAvgCost = decAvgCost + txtCost.Text
            intLargestFreq = intLargestFreq + cboxAisle.SelectedItem
            intLeastFreq = intLeastFreq + cboxAisle.SelectedItem
            txtCost.Clear()
            txtCost.Focus()
        End If
    End Sub

    Private Sub btnFinalise_Click(sender As Object, e As EventArgs) Handles btnFinalise.Click
        Array.Sort(arrAisle)
        For i As Integer = 0 To intIndex
            intCurrentElement = arrAisle(i)
            If intCurrentElement = intCurrentValue Then
                intElementFreq += 1
            ElseIf i > 0 Then
                If intElementFreq > intLargestFreq Then
                    lblMost.Text = arrAisle(i - 1)
                    intLargestFreq = intElementFreq
                ElseIf intElementFreq < intLeastFreq Then
                    lblLeast.Text = arrAisle(i - 1)
                    intLeastFreq = intElementFreq
                End If
                intCurrentValue = intCurrentElement
                intElementFreq = 1
            End If
        Next
        decAvgCost = decAvgCost / intIndex
        lblMost.Text = "Most Items - Aisle:" & intLargestFreq
        lblLeast.Text = "Least Items - Aisle:" & intLeastFreq
        lblTotal.Text = "Total cost per item : " & FormatCurrency(decTotalCost)
        lblAverage.Text = "Average cost per item : " & FormatCurrency(decAvgCost)
    End Sub
End Class

as you can see, i need the most frequently chosen numbers from the cboxAisle to be shown in lblMost and the least frequently chosen number to be shown in lblLeast.

Thanks :) :)
Viewing all 26485 articles
Browse latest View live




Latest Images