Visual Basic.NET

94K

Solutions

24K

Contributors

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,

Share tech news, updates, or what's on your mind.

Sign up to Post

Hello,

I have a vb.net grid bound to a table. There many ways that I have designed in to search the data in the table. All is well until I want to reorder the columns. Specifically I want to place the term searched 'search' field in the first column. The column name below for [state] works great. The column name for [Last Name] does not work; instead throwing an exception indicating the data field is not found. I am sure that the field name is correct as I have copied it out of the grid properties into the code. I tried other single word fields which all work fine. Fields such as [First Name] and [Last Name] don't work at all with the same exception taken.

I surmise that I need to wrap the "two-word" field names differently. Ideas?

 Does not work: Master_ContactsDataGridView.Columns("Last Name").DisplayIndex = 1
 Works: Master_ContactsDataGridView.Columns("State").DisplayIndex = 2
0
OWASP: Threats Fundamentals
LVL 19
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

The code below creates a list of strings that I would like to sort by date, but there are 2 problems. First, the date is within the string, but it can be grabbed by splitting the string and grabbing the 3rd segment - Results(x).Split(""""c)(3). The string is being split by quotes. Second, the date will contain a string like this 7/21/2019 or 11/9/2019. I think this might be an issue because it's not mm/dd/yyyy.  Month or Day could be 1 or 2 characters (not sure if that really matters).

I am thinking DateTime.Compare and DateTime.Parse would be used, but I'm not sure how I would use them to get the list in order of date. The list will contain strings that look like this...

"-419.56","7/9/2019","Company","Product","RAS-201459"

In the code below, the date for the first item in the List is outputted, but I want to sort the List by date. Does someone know how this can be done? Thanks!

    Private Sub btnSaveReport_Click(sender As Object, e As EventArgs) Handles btnSaveReport.Click
        Try
            Dim strSourceFileLocation As String = AppDomain.CurrentDomain.BaseDirectory + "_data/"
            Dim strDetinationFileLocation As String = tbSaveFileLocation.Text
            Dim Paths() As String = IO.Directory.GetFiles(strSourceFileLocation, "*.code")
            Dim Results As New List(Of String)()
            For Each Path As String In Paths
                For Each line As String In File.ReadAllLines(Path)
                    If line.Contains("RAS-") Then

Open in new window

0
I have the following code that iterates thru files ending in .dat within a folder. Now what I want to do is go into each file and grab one line at a time, and if that line contains "PO-", then I want to put it into an array. I'm thinking I need another loop (maybe another Next loop?). Can someone help me to grab lines containing "PO-" within these files and put them into an array? Thanks!
    Private Sub btnSaveReport_Click(sender As Object, e As EventArgs) Handles btnSaveReport.Click
        Try
            Dim arrayPOentries() As String
            Dim strSourceFileLocation As String = AppDomain.CurrentDomain.BaseDirectory + "_data/"
            Dim strDetinationFileLocation As String = tbSaveFileLocation.Text
            Dim Paths() As String = IO.Directory.GetFiles(strSourceFileLocation, "*.dat")
            For Each Path As String In Paths
                'another loop here?
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Me.Close()
    End Sub

Open in new window

0
Hi All,

I have problem with datagridview cell click event.
Please see below code. It does not work as I want to.

When column "Pilih" is checked then QtyPilih should be filled from "TotalStok".
When column "Pilih" is uncheck the QtyPilih should be set to 0.

 Private Sub dgvData_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvData.CellClick

        blnGridOnFocus = True

        With dgvData

            If e.RowIndex < 0 Then Exit Sub
            If e.ColumnIndex < 0 Then Exit Sub

            Dim dgvRow As DataGridViewRow = .Rows(.CurrentRow.Index)

            Dim strColumnName As String = ERV_Global.Get_Column_Name_From_Datagridview( _
                          dgvData, _
                          e.ColumnIndex)

            Select Case strColumnName

                Case "Pilih"

                    Dim blnPilih As Boolean = .Rows(e.RowIndex).Cells(e.ColumnIndex).Value

                    .Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not blnPilih

                    If blnPilih = False Then

                        If dblMaxQty > 0 Then
                            dgvRow.Cells("QtyPilih").Value = dblSisaQty

                            If dgvRow.Cells("TotalStok").Value > dblSisaQty Then
                                dgvRow.Cells("QtyPilih").Value = dblSisaQty
                            Else
                                dgvRow.Cells("QtyPilih").Value = dgvRow.Cells("TotalStok").Value
                            End If
     

Open in new window

0
Using visual studio 2017, and a VB.net project, we use the resources.resx to execute SQL queries to update the live databases of the clients using our project (We add .txt files with queries in, and then run and update the database). The database is MS SQL2017.

I have added a query that will not run the first time I execute it (for example when I first install the program and all queries have to run), but if I go and manually update the "database version" in the project to not include the latest failed script but rather shows the previous one, it then runs fine. Meaning anyone updating to the newest version does not miss the script, but any new installations does and needs to then be run manually.

The script is simple :  

USE [Vetmaster]
GO

      UPDATE [dbo].[Role]
      SET [Admin] = 0
      GO
      
      INSERT INTO [dbo].[ScriptVersion]
           ([Version])
VALUES ('DB2.0.1.96')
GO

The ScriptVersion is just a table we created to make sure the scripts complete, and if for any reason it does not completely run, that version does not get written into the table.

Why would the code not run on the first attempt but run fine during a second attempt or update?
Please let me know if any more information is needed.

regards,
Louis.
0
Hi,

I have a form that worked well until I used it on a separate machine with higher resolution than the machine I used to develop it.
1. The form paints as expected and fits the screen size perfectly.
2. Any action (such as a button to set a filter) causes the app to resize to roughly 1/4 the original size.

Up until this point I did not have issues with this. I [thought] that 2019 came some way forward with the resizing issues but I'm sure I missed a key point of it along the way. I read up on perform auto size but I have not been able to place that code anywhere that has made a difference.

Thoughts?
0
Hello,

When attempting to run my project, I receive the following error message for several Forms in my project. How do I solve this issue?

Error:

Couldn't process file Form4.resx due to its being in the Internet or Restricted zone or having the mark of the web on the file. Remove the mark of the web if you want to process these files.      AOP-VOL1

Thanks,

Victor
0
I'm having issues with a piece of software that relies on a connection to a specific SSID using a wireless USB NIC.

The software relies on data sent to the computer from a scanning tool that connects to the same local network as the computer, it's relatively rare but we have problems with windows autoconnect working with the adapters we provide to the clients.

I'm looking for a way to check if the connection is working, and if it is not, to connect the wireless adapter to the SSID when the software is started.
 I'm using VB.net and C#.

If there is any other info you need I'll be happy to provide it.
1
Hello,

I have a two part Boolean based filter that I need to apply.  Seemingly I have run every combination except for one. The 'one' part is where I need help! I've included one version of what I've tried bellow to give the idea of what I need to do.

Email: a field from a bound table
POC_email: a field from a bound table
CompanySearch.is a text box that the user enter their needed terms (e.g. 'Edward')

The concept is that I would like to return all record where the field data includes the search term indicated in 'companysearch.text'

Sample non working code:
Master_ContactsBindingSource.Filter = "email like '" & CompanySearch.Text & "*'" Or "POC_email like '" & CompanySearch.Text & "*'"
0
How do I open an Access Database and Fill a ListBox in VB.Net Code
0
Python 3 Fundamentals
LVL 19
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Hi Experts,

I'm running VS2013.

The Main form of my production app, when viewed in Design View, just appears as an empty form:

Design View screen
But when I run the project, all the expected controls appear:

Run time screen
I want to do more work on the form in design view - how can I restore the real form in design view?

The source files are here.

Regards,
Leigh
0
I have a vb.net program and I don't want the form to be visible.  I tried using both Me.Hide and Me.Visible = false in the Form Load sub, but the form still shows. I thought there was a setting in the properties of the form in Visual Studio that could be set to hidden, but I can't find such a setting.

The only way I could get it to be hidden was to set the Opacity to 0%, but I thought there was a setting in Visual Studio or vb code that would accomplish this.
0
In SQL Server 2012, why won't the following dynamic SQL statement execute?

SELECT DISTINCT 7 As EntityId, E7Id As InstanceId FROM ##TempTable_461_0 UNION SELECT DISTINCT 1 As EntityId, E1Id As InstanceId FROM ##TempTable_461_0

Note: I verified that ##TempTable_461_0 has the columns "E7Id" and "E1Id".
0
how to get csv file in a treeview.
I am using vb.net desktop.

regards
0
I am looking at the datatables example of parent/child, and it has the server side code written in PHP to pull the data.

 Can you please explain/convert this into VB.NET or C# so I can understand how to use it with my own data?

https://datatables.net/blog/2019-01-11

The sites.php and users.php appear to be under the "server-side php" topics.

Editor::inst( $db, 'sites' )
    ->fields(
        Field::inst( 'id' )->set( false ),
        Field::inst( 'name' )->validator( 'Validate::notEmpty' )
    )
    ->join(
        Mjoin::inst( 'users' )
            ->link( 'sites.id', 'users.site' )
            ->fields(
                Field::inst( 'id' )
            )
    )
    ->process( $_POST )
    ->json();

Open in new window



if ( ! isset($_POST['site']) || ! is_numeric($_POST['site']) ) {
    echo json_encode( [ "data" => [] ] );
}
else {
    Editor::inst( $db, 'users' )
        ->field(
            Field::inst( 'users.first_name' ),
            Field::inst( 'users.last_name' ),
            Field::inst( 'users.phone' ),
            Field::inst( 'users.site' )
                ->options( 'sites', 'id', 'name' )
                ->validator( 'Validate::dbValues' ),
            Field::inst( 'sites.name' )
        )
        ->leftJoin( 'sites', 'sites.id', '=', 'users.site' )
        ->where( 'site', $_POST['site'] )
        ->process($_POST)
        ->json();
}

Open in new window


Thanks!

Starr
0
I obtained this code from the internet but it gives integer results.  How do I modify it so it will compute to 2 decimal places?  I am dealing with dollars and cents.

Public Shared Value as Integer=0
  Public Shared Function GetValue(Item as Integer) as Integer
     value= value + Item
     return Item
  End Function
  Public Shared Function GetTotal()
     return value
  End Function
1
I can get Date variable to match sql server date to use in code to find indexed line in database table.  I have tried multiple formatting options - nothing works.  I need to include miliseconds in the vb.net Date format - not in string format.  I use this in a <= operations to compare date to the database.  When it is = it uses that indexed line to include in the charted data.  Everything I have tried gives me date and time without miliseconds.

I have tried the following.

Dim MaxDate As Date = DataTable.Rows(0)(0)
MaxDate = Date.ParseExact(DataTable.Rows(0)(0), "yyyy-MM-ddTHH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)

I can convert using a string variable, but cannot use string variable in query search for date.
0
Hi,

I have create 2 classes. the problem is following List no records is showing
public class DirectoryResponse
    {
        public List<Company> Companyname { get; set; }
    }


    [XmlType(TypeName = "Company")]
    public class Company
    {
    public string _id { get; set; }
    public string  name { get; set; }
    public string friendly_id { get; set; }
    public DateTime creation_date { get; set; }
    public DateTime updated_date { get; set; }
    public int member_count { get; set; }
    public string initial { get; set; }

    
    





    }

Open in new window


Call form following class

RestAPI1 Class

public  List<Company> GetCompanyDetails(bool onlyCurrent = true)
        {


 var raw = response.Content.Replace("Date\":\"0000-00-00\"", "Date\":null").RemoveTroublesomeCharacters();
                var package = JsonConvert.DeserializeObject<DirectoryResponse>(raw);
                // return JsonConvert.DeserializeObject<T>(s);
                //raw.FromJson<DirectoryResponse>()



                if (package != null)
                {


                    var com = package.Companyname;

                    return com;
}

Open in new window


No errors . But no records returning. When it's debug raw variable get all the results.
But package.Companyname is not getting results


 Interface of  RestAPI1 Class
public interface IrestClient
    {
        List<Company> GetCompanyDetails(bool onlyCurrent = true);
    }

Open in new window

0
I want to create a VB.net or C# program that goes thru a text file, and when it finds this text...

"region": "us-east",

on a line, it will output the next line to a new file.  When the program finishes running, all lines that were found after that text will have been added to the new file.

This is something I know I could search online and figure out, but it would take me time to work it out and I need to pull this information as soon as possible. If someone can show me code that will accomplish this, I would greatly appreciate it!
0
Bootstrap 4: Exploring New Features
LVL 19
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

We have an existing VB.NET program which was used to make files created by serializing an object using the BinaryFormatter.  Now we have a new program that needs to deserialize those files to create the corresponding objects.  The class definition was copied directly from project A to project B, however the process fails with the following error:

"Unable to cast object of type 'ProjectA.myObject' to type 'ProjectB.myObject'."

when I try to do the following:

MyObject1 = CType(BFormatter.Deserialize(readFile), myObject)


It looks like the serialization process incorporated the namespace of Project A into the definition of the serialized object, but I do not need it.  If I were starting from scratch, I would have done this differently (e.g. use XML serialization, instead of binary), however we have many clients with these files serialized using ProjectA that will need to have them loaded into ProjectB.  Is there any way to work around this problem?  Thanks.
0
We have an app written in Visual Studio 13 using VB.  It runs fine on windows 7 but when we try to run it on windows 10 we get the attached error.

Win10 VS2013 error  sql-error-details.rtf

The pc the app was developed on is running .net 4.6.1.  The CrystalDecision extensions checked in the image should have been included in the build.

CrystalDecsionExtensions
Any ideas what we need to do to get the app to run?

thanks in advance for your help.
0
I have written a page that posts data for a client into the above, It works as part of a new website as the only page (used for testing) when I copy the code or paste the page into the web application I have been developing it for I get an error, I've used Nuget to ensure all the correct dll's are added.

This is the error

"An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host"

This line is causing the error:
Dim myresponse As HttpResponseMessage = client.SendAsync(myrequest).Result


Can anyone suggest a solution or reason why the same code fails in one web application but not the other?

Here is the code

Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading.Tasks
Imports Microsoft.IdentityModel.Clients.ActiveDirectory
Imports Newtonsoft.Json.Linq
Imports System.Collections.Generic
Public Class CRM_Contact
    Inherits System.Web.UI.Page

    Public myclientId As String = Convert.ToString(ConfigurationManager.AppSettings("clientid"))
    Public redirectUrl As String = Convert.ToString(ConfigurationManager.AppSettings("redirecturl"))
    Public serviceUrl As String = …
0
I'm using a select2 multiple dropdownlist. I am getting the above error.
I've seen posts where they say this error occurs if you have two items in the list with the same value, but I do not have that and I also use the "multiple" option.

    <select name = "ctl00$ContentBody$TeamProfileControl$ddlDistrictId" id="ddlDistrictId" Class="ddlSelectMultiple" name="ddlDistrictId" multiple="multiple" style="width:100%;">
    	<option value = "1786" > AP_Test_District</Option>
    	<option value = "209" > Honey Dew South</Option>
    	<option value = "562" > HQ</Option>
    	<option value = "38" > JK&#39;s Crib</Option>
    	<option value = "206" > Kansas City Office</Option>
    	<option value = "759" > Testing District</Option>

    </select>

Open in new window


I also read to add items this way, however, I populate with a sql databind, so using this is not applicable:
DDLModality.Items.Add(Li1)

I need to preselect the previously saved values in the dropdownlist to display them as selected on the screen. Here is my code, it runs with no errors but when the screen is loaded it generates:
Cannot have multiple items selected in a DropDownList.

   Public Sub CheckMultiListBoxNumeric(ByRef ddlDistrictId As DropDownList, ByVal districtIds As String)

        ddlDistrictId.ClearSelection()

        Dim checkedItems As String()
        checkedItems = Split(districtIds, ",")
        Dim selected As List(Of String) = checkedItems.ToList()

        For Each row As String In selected


            If ddlDistrictId.Items.FindByValue(row) IsNot Nothing Then
                ddlDistrictId.Items.FindByValue(row).Selected = True
            End If


        Next

Open in new window

0
I want to send some commands to minecraft on windows 10...specifically to hold down the 'W' key so that my game will move forward for X miliseconds, then release, then send a spacebar to "Jump".  Using sendkeys doesn't work so well for me because they send single keystrokes and I'd like to hold keys down.  How can I do this?  I use vb.net 2017.  Thank you!
0
I have a text box control which accepts numeric numbers as a string. So how can I strip off any leading zeroes before any type of conversion to a numeric?
 if someone enters any of the following for example I need to strip off the leading 00s :
"0056"
"06"

I have tried the following but it is not working:
If txtNumInput.Text.Trim = txtNumInput.Text.Trim.TrimStart('0') ' This wont work

If txtNumInput.Text.Trim = txtNumInput.Text.ToString.Trim.TrimStart('0') ' This also won't work
0

Visual Basic.NET

94K

Solutions

24K

Contributors

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,