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

Need help with Subtraction and variables

$
0
0
Hello,

I have a few If-Then statements and the final one that I need is to basically "subtract 1 from every 5"

In my case, for every 5 miles traveled I need to subtract 1 year of life - its a wackly problem that I have.

How can I code this? Googling this results in a bunch of time subtraction links - that's not really what i need though.

Thanks!

VS 2010 Need help with Multi-form project

$
0
0
Hello,

I'm currently working on a project that takes information from multiple selected listboxes each on different forms.
From there it's supposed to add a price based on the selected choice but for some reason it isn't working.

Can somebody please help me to understand what i'm doing wrong?

https://www.dropbox.com/s/btcm7do2wr...%20it%20it.zip

Thank you so much :D

-Logan

VS 2010 [RESOLVED] Confused on Random

$
0
0
I just noticed that my random numbers are NOT random. They always start at a certain number, and generate the same sequence every time my program runs anew. Here is an example of my code within the sub button_click:

Code:

Dim rando As String = CInt(Int((3 - 1 + 1) * Rnd() + 1))

                If rando = 1 Then

                    For Each ele As HtmlElement In WebWindow.WebBrowser1.Document.All
                        If ele.GetAttribute("id").ToLower = "RadioGroup0".ToLower Then
                            ele.InvokeMember("click")
                        End If
                    Next
                End If

I use a different version of this for different elements, but the results are the same. Random is not random. On other forums, they say to put your Rnd outside the loop, which in this case it is, but it's still not random! Whatever "seed" was used when I made the program is always the same seed that is used whenever the program runs and I don't know how to change that. Help?

Bubble Maker

$
0
0
Could someone please tell me if I am doing this right. I know I am not because it won't work but am I even close? I am trying to take a png file and use that to make a balloon in that shape on a pictureBox(someone suggested yesterday). The bubbles are supposed to float to the top of the vat and then pop. I looked at my book and tried it from there. I put a pictureBox on my panel and then imported the (andy.png) into the pictureBox. When I run it a page opens up (application designer.vb) with a line with green in it. Is it possible to do what I need to do this way? I am really lost. Any help would be greatly appreciated.

I have a bunch of stuff commented out.




Form1.vb:
Public Class Form1
Private Foam As New List(Of Bubble)
Private CurrentAge As Integer
Private Rand As New Random
Dim x_intercept(0, 0)
Dim y_intercept(0, 0)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
timBubbleTimer.Interval = 100
timBubbleTimer.Enabled = False
pnlVat.BackColor = Color.LightGray
End Sub

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Foam = New List(Of Bubble)
CurrentAge = 0
Dim g As Graphics = pnlVat.CreateGraphics
g.FillRectangle(New SolidBrush(Color.LightGray), pnlVat.DisplayRectangle)
timBubbleTimer.Enabled = True
timBubbleTimer.Start()
End Sub

Private Sub timBubbleTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timBubbleTimer.Tick, PictureBox1.Move
CurrentAge += 1
Dim PX As Integer
Dim PY As Integer
PX = 10
PY = 10
Static Count
Count = (Count + 1) Mod 2
If Count = 1 Then
PictureBox1.Image = Image.FromFile("Andy.png")

Else
PictureBox1.Image = Image.FromFile("NoAndy.png")
End If

PictureBox1.SetBounds(PictureBox1.Left + PX, PictureBox1.Top + PY, 0, 0)
If (PictureBox1.Top + PictureBox1.Height) > Height Then PY = -PY
If PictureBox1.Top < 0 Then PY = -PY
If (PictureBox1.Left + PictureBox1.Width) > Width Then PX = -PX
If PictureBox1.Left < 0 Then PX = -PX
Count = (Count + 1) Mod 3
Select Case Count
Case 0
PictureBox1.Image = Image.FromFile("Andy.png")
Case 1
PictureBox1.Image = Image.FromFile("NoAndy.png")
End Select


'Dim MaxX, MaxY As Integer
'MaxX = pnlVat.Width
'MaxY = pnlVat.Height

'Dim g As Graphics
'g = pnlVat.CreateGraphics
'Dim p As New Point(0, 0)



'PX = Rand.Next(4, MaxX - 4)
'PY = Rand.Next(MaxY - 34, MaxY - 4)
'p = New Point(PX, PY)
'Foam.Add(New Bubble(p, Brush.newColor, Pen.DimGray))

'pnlVat.Refresh()

'For i As Integer = 0 To Foam.Count - 1 Step 1
' If Foam(i).GetLocation.X > MaxX Then
'Foam(i).Remove(g)
'Foam(i).GetLocation()

' End If
'If Foam(i).GetLocation.Y < 0 Then
' Foam(i).Remove(g)
' Foam(i).GetLocation()

'End If


'' Foam(i).Remove(g)

'Foam(i).Move()
'Foam(i).Draw(g)
'Foam(i).Grow()


'Next


' Add code here to create, move, resize, erase and redraw all the bubbles in the Foam list

End Sub

Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
timBubbleTimer.Stop()
timBubbleTimer.Enabled = False
End Sub


End Class


Bubble.vb


Public Class Bubble
Private BubSize As Integer
Private BubColor As Color
Private BubOutlineColor As Color
Private BubLocation As Point
Private BubAge As Integer
Shared Graphics As Graphics



Public Sub New(ByVal NewLoc As Point, ByVal NewColor As Color, ByVal NewOutlineColor As Color)
'Dim New List As New Bubble

' Initialize the attributes of a new bubble here
Dim g As Graphics = Bubble.Graphics
BubColor = Color.Aqua
BubOutlineColor = Color.AntiqueWhite
'BubLocation = (y)
BubAge = 0
BubSize = (1)








End Sub

Public Function GetLocation() As Point
Return BubLocation
End Function

Public Function GetSize() As Integer
Return BubSize
End Function

Public Sub Move()
Move()

' Add code here to change a bubble's location

End Sub

Public Sub Remove(ByVal g As Graphics)
Remove(g)



' Add code here to remove a bubble from the list

End Sub

Public Sub Draw(ByVal g As Graphics) ' Add code to draw the current bubble

'Dim myPng As Image("andy.png", "noAndy.png")
'Dim g As Graphics = Graphics.FromHwnd(PictureBox)
''g.DrawImage(myPNG, 150, 200)
'Dim myBrush As System.Drawing.Brush()
'Dim BubGraphics As System.Drawing.Graphics
'BubGraphics = Bubble.CreateGraphics()
'formGraphics.DrawEllipse(Brush, New Rectangle(0, 0, 200, 300))
''myBrush.Dispose()
'BubGraphics.Dispose()



' Dim width As Integer = bm.Width - (bm.Width * percentResize) 'image width.

' Dim height As Integer = bm.Height - (bm.Height * percentResize) 'image height



' g.DrawImage(bm, New Rectangle(0, 0, width, height), New Rectangle(0, 0, bm.Width, _
'bm.Height), GraphicsUnit.Pixel)

' g.Dispose()

' bm.Dispose()

End Sub
Public Sub UnDraw(ByVal g As Graphics)
UnDraw(g)

' Add code to erase the current bubble from the display

End Sub

Public Sub Grow()
BubSize += 1
End Sub

End Class



Application designer.vb

<auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.261
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On


Namespace My

'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication

<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub

<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Suds.Form1 This is the one that keeps showing up.
End Sub
End Class
End Namespace

IF, then, Else Functions errors

$
0
0
This may seem like a stupid question but I can't seem to get the IF function to work. I got it to work in an earlier section:
Code:

If txtSat1.Text = "" Then
            If txtSat2.Text = "" Then
                If cbSat.CheckState = 0 Then
                    MessageBox.Show("Please Enter Hours for Saturday")
                End If
            End If
        End If

but with my current code here:
Code:

If txtSun1.Text <> Then
            cbSun.CheckState = 0
            Else If txtSun2.Text <> Then
            cbSun.CheckState = 0
        End If

Both the "Then"s are underline blue and it says "expression expected." I have two textboxes and a checkbox. If the user types something into either one of the textboxes, then I want the checkbox to not be able to be clicked. Any help would be appreciated.

[Solved] One table not updated using VB 2010 Express and SQL Server 2008 Express DB

$
0
0
I have a Managers table and a Dealership table in my SQL Server 2008 Express Database. (I'm new to SQL Server)

I am using the code below to update the dataset. Changes to the Dealership table are not being reflected in the dataset. They show immediately after the update, but if I close the project and reopen the project, the changes are missing. Changes to the Manager file are reflected just fine.

I just noticed that my TableAdapterManager says "ManagersTableTableAdapter" in properties and there is no TableAdapterManager for the DealershipTable.
Is this OK or not?

What could cause this??

undefined Code:
  1. Me.Validate()
  2.     Me.DealershipTableBindingSource.EndEdit()
  3.     Me.ManagersTableBindingSource.EndEdit()
  4.     Me.TableAdapterManager.UpdateAll(Me.DeiServerDBsDataSet)

Scale Graphics to Image or create custom co-ordinates?

$
0
0
Hey,

I am currently working on drawing out wire diagrams , I get all the co-ordinates from another program and simply draw them out in a picture box.

vb.net Code:
  1. Private Sub test(Optional mark As Boolean = False)
  2.  
  3.         Dim Img As New Bitmap(PictureBox1.Width, PictureBox1.Height)
  4.  
  5.         Dim g As Graphics = Graphics.FromImage(Img)
  6.  
  7.         g.Clear(Color.White)
  8.  
  9.         Dim graphiccounter As Integer = 0
  10.      
  11.         Dim result As Object
  12.         'Needed to get co-ordinates
  13.         Dim x() As Object
  14.         Dim y() As Object
  15.         Dim z() As Object
  16.         Dim results As Object
  17.  
  18.         'Will take in x and y values from objects above
  19.         Dim x_loc(0) As Integer
  20.         Dim y_loc(0) As Integer
  21.  
  22.  
  23.          _Paths.Clear()
  24.         namepath.Clear()
  25.  
  26.         For Each row As DataGridViewRow In DataGridView2.Rows
  27.  
  28.             If row.Visible = True Then
  29.                 'sets variables to nothing, needed in order to run certain commands
  30.                 results = Nothing
  31.                 x = Nothing
  32.                 y = Nothing
  33.                 z = Nothing
  34.  
  35.              
  36.  
  37.                 'get the co-ordinates and stores them in x,y,z. results will contain the number of co-ordinates stored.
  38.                 result = cor.GetPath(x, y, z)
  39.                
  40.                 're declares variables based on how many co-ordinates
  41.                 ReDim x_loc(result)
  42.                 ReDim y_loc(result)
  43.  
  44.  
  45.          
  46.                 counter = 1
  47.  
  48.                 _Paths.Add(New GraphicsPath)
  49.                 namepath.Add(New NamedPath)
  50.                 For k = 1 To result - 1
  51.  
  52.                     x_loc(k) = (x(k))
  53.                     y_loc(k) = PictureBox1.Height - (y(k))
  54.                     x_loc(k + 1) = (x(k + 1))
  55.                     y_loc(k + 1) = PictureBox1.Height - (y(k + 1))
  56.                     spacer += 5
  57.  
  58.                    
  59.                         _Paths(graphiccounter).AddLine(x_loc(k), y_loc(k), x_loc(k + 1), y_loc(k + 1))
  60.                         namepath(graphiccounter).Name = row.Cells("Core_Id").Value
  61.                         namepath(graphiccounter).Path = _Paths(graphiccounter)
  62.                         'g.FillEllipse(Brushes.Black, x_loc(k + 1) - 4, y_loc(k + 1) - 4, 8, 8)
  63.  
  64.                         counter = counter + 1
  65.          
  66.  
  67.                 Next
  68.  
  69.  
  70.                 _Pen = New Pen(Brushes.HotPink, 5)
  71.                 g.DrawPath(_Pen, namepath(graphiccounter).Path)
  72.                 graphiccounter += 1
  73.  
  74.  
  75.                 '  Console.WriteLine("New Line")
  76.             End If
  77.         Next
  78.      
  79.         PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
  80.         PictureBox1.Image = Img
  81.  
  82.     End Sub

So that is my code, some of the code may look funky, but that is because I am using a COM object and Windows Script Host Model.

The results I get back in x and y and co-ordinates based on the other program's co-ordinates. Ofcourse it is easy for me to adjust the co-ordinates so that it works on my screen but how would I go about drawing it so that the image automatically redraws to size based on the window?

Is it possible to set the co-ordinate system of the GDI graphics? For example a setting to tell windows that every 10 points is just 1.

so for the picture box of height 100x100. The co-ordinates start at 0 and go to 400, making each point in the picturebox actually 0.25.

I am looking around for answer but any suggestions is appreciated :)

Inserting flags based on user-input

$
0
0
I have a small software inside which there is a facility to select which country, Now i have a database of around 150 flags uploaded to My.Resources.

I first started using this code.

Code:

      Select Case TextBoxCountry.Text

              Case is = "England"
              PictureBox.image = My.Resources.England
              Case is = "USA"
              PictureBox.image = My.Resources.USA
              Case is = "Austraila"
              PictureBox.image = My.Resources.Australia

and soo on,

But do i have to do this to all the 150 flags?? isn there a simple way??

I have named all the resource images to the names of their country exactly. Eg: India.jpg, Australia.jpg etc

Cant i use this somehow??

And is there a way that i can make it case-insensitive so that if the user enters it in improper case also it will recognise it??

Thank You.

Reboot

$
0
0
Hi guys,

Instead of using a .cmd file and programming to launch after xx processes, can I launch my form (Reboot form) after all other processes........

Find out what page as start page

$
0
0
I downloaded a vb.net sample.
There are many folders under project as sub-project.
Once I open sln file and run it, all folders display on the start page as buttons.
How to find out which page is start page?
I tried to find out prom property form the project but no more info.

VS 2010 [RESOLVED] Adding Events To Custom Controls

$
0
0
I have a custom control that has a series of comboboxes. In my application, I programmatically add the control to several programmatically created tabs. When the first combobox value is changed, I would like to iterate through each of the controls and set their value to match. I know how to iterate through the tabs and find a particular combobox within each control, but I haven't been able to figure out how to assign an event to those comboboxes to trigger the search in the first place.

How does one assign an even to a subcontrol within a custom control?

[VB.NET] Fill combobox from MySQL!

$
0
0
Hey guys!

I've got a combobox, and I need to fill it up with data from a column in a MySQL table. When one of the cells is selected, the data in the cell in the next row(on the right) is displayed in a textbox. I know how to create a connection, but I can't figure out how to do the rest. I've searched on internet but without brilliant results. Assuming I the table is like this:

Name|Url
Hello | hello.com
BLA | bla.com

Thanks in advance?

ado - insert from one DB to another

$
0
0
Hi all, not too sure on how to craft this sql, I want to insert into an access database on a share path, from another access database on a share path, in vb.net using

Code:

        Dim cmd As OleDbCommand = New OleDbCommand()
        Dim sConStr As String = "Provider=Microsoft.jet.oledb.4.0;data source=localdb"
        Dim conn As OleDbConnection

        conn = New OleDbConnection(sConStr)

        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SQL GOES HERE"              'INSERT INTO localdb SELECT table1 from DB2 ?

        conn.Open()
        cmd.ExecuteNonQuery() 'this should execute the sql to add the table
        conn.Close()

I cant seem to get the syntax right, does anyone have an example of that?

Try and Catch with outlook

$
0
0
With this code i send a email with outlook.


Code:


 Dim application = New Microsoft.Office.Interop.Outlook.Application
        Dim outlookEmail = CType(application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem), MailItem)

        outlookEmail.To = "*********@gmail.com"

        outlookEmail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain

        outlookEmail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal

        outlookEmail.Body = ("Test")
        outlookEmail.Subject = ("Ok")

        outlookEmail.Display(False)
        outlookEmail.Send()

it works great , but when there is no outlook on the pc installed the programma crash.

Try and catch is not working ?

The error is

Code:

'Catch' cannot catch type 'Microsoft.Office.Interop.Outlook.Exception' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Who can help me ?

Cant obtain Access Token. Unauthorized exception. Help?

$
0
0
It seems that Dropbox wont let me obtain access token. Any suggestions?
Steps 0-3 work fine but it stops on step 4 and gives and 'unauthorized exception' warning. I have entered the correct
consumer key and secret and it seems to accept those fine and wants to connect the users account to the application.
However it hangs on step 4.


Code:

Imports AppLimit.CloudComputing.SharpBox
Imports AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox
Imports System.IO


Public Class Form1

    ' enter the consumer key and secret
    Dim ConsumerKey As String = "MyKey"
    Dim ConsumerSecret As String = "MySecret"

    ' get the config of dropbox
    Dim config As DropBoxConfiguration = TryCast(CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox), DropBoxConfiguration)
    Dim requestToken As DropBoxRequestToken

    Private Sub RequestButton1_Click(sender As System.Object, e As System.EventArgs) Handles RequestButton1.Click

        ' 0. set your own callback which will be called from DropBox after successful authorization
        config.AuthorizationCallBack = New Uri("http://www.google.com")

        ' 1. create a request token
        requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, ConsumerKey, ConsumerSecret)

        ' 2. build the authorization url based on request
        Dim AuthorizationUrl As String = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken)

        ' 3. Redirect the user to the website of dropbox
        Process.Start(AuthorizationUrl)

    End Sub

    Private Sub SaveTokenButton2_Click(sender As System.Object, e As System.EventArgs) Handles SaveTokenButton2.Click

        ' 4. Exchange the request token into access token
        Dim accessToken As ICloudStorageAccessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config, ConsumerKey, ConsumerSecret, requestToken)

        ' 5. Open the storage with the generated access token
        Dim DropboxStorage As New CloudStorage()
        DropboxStorage.Open(config, accessToken)

        ' 6. write token for later use
        Dim tokenstream = DropboxStorage.SerializeSecurityToken(accessToken)
        Dim tokenfile As New FileStream("c:\MyToken.txt", FileMode.Create)
        tokenstream.CopyTo(tokenfile)
        tokenfile.Close()

        ' 7. close the storage
        DropboxStorage.Close()

    End Sub


Connection string to MSSQL 2008 VB.NET

$
0
0
Hi Guys, I'm working on some app which have to connect to the database (MSSQL2008).
My connection string looks as follow:

Code:

#Region "[--------First of all you need database connection be set up---------]>"
    Public Function GetConnection() As OleDbConnection
        '[-------------Below is for MS SQL Server 07 / 2000 Connection String------------------]>
            Dim strConn As String = "Server=JMPANOPIO;UID=sa;PWD=123456; Database=AHD"

        Try
            Dim Conn As OleDbConnection = New OleDbConnection(strConn)

            If Conn.State <> ConnectionState.Open Then
                Conn.Open()
            End If

            Return Conn
        Catch
            Throw New Exception("The connection with the database can't be established.")
        End Try
    End Function
#End Region

Of course dosen't work [Exception Details: System.Exception: The connection with the database can't be established.]. I suppose the reason I cannot to get MSSQL is that the string is old. Anyway can You please tell me how the connection string should looks like?

VS 2010 Alternative to default webbrowser control?

$
0
0
the default webbrowser controls with vb.net 2010 no longer seem able to function with my project.
(don't ask me why, they just won't. they stop navigating. LINK)

a webbrowser control is still the best solution for this function of the project
it frees me from having to hard code things into my program for each update where i might change my website.

does anyone know of any OTHER webbrowser controls out there?

VS 2010 Winsock, hamachi, ''The requested address is not valid in its context''.... Help! =S

$
0
0
Hello all,

This is my first post on this forum, so first short introduction, I'm Daniël, a 17 year old programmer with an obsession for aviation... Today i started writing an application to fly so-called "shared cockpit" in Microsoft Flight Simulator. This application should include both the possibilities to serve as server or as client, connect to the other program over hamachi (so, on a specified IP address), then start sending data to synchronize both cockpits and planes. I decided to start with the connection part, as this is where I have the least experience with. Here is what I wrote so far (examples on the internet generally use much more code so maybe this looks stupid to you, but please remember this is the first time i work with winsock :sick:):

Code:

Option Explicit On

Imports FSUIPC
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Public Class Form1

    Dim FSUIPCconnected As Boolean = False
    Private isConnectedFlag As Boolean
    Private Client As TcpClient
    Private Server As TcpListener
    Private mobjClient As TcpClient
    Private mode = 0 '0 is server, 1 is client

    Dim bytes(256) As Byte
    Dim data As String = Nothing

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        TextBox2.Text = "1544"
    End Sub

    Private Sub button1_click() Handles Button1.Click
        If isConnectedFlag = False Then
            Try
                Label4.Text = "Listening.."
                Server = New TcpListener(IPAddress.Any, Convert.ToInt32(TextBox2.Text))
                Server.Start()
                mobjClient = Server.AcceptTcpClient
                Label4.Text = "Connected"
                isConnectedFlag = True
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Else
            If MsgBox("Are you sure you want to disconnect?", MsgBoxStyle.YesNo, "FS-Share") = MsgBoxResult.Yes Then
                Client.Close()
                Server.Stop()
            End If
        End If
    End Sub

    Private Sub button2_click() Handles Button2.Click
        If isConnectedFlag = False Then
            Try
                Dim EP As New IPEndPoint(IPAddress.Parse(TextBox1.Text), Convert.ToInt32(TextBox2.Text))
                Client = New TcpClient(EP)
                If Client.Connected = True Then
                    Label4.Text = "Connected"
                    isConnectedFlag = True
                Else
                    Label4.Text = "Not Connected"
                    isConnectedFlag = False
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Else
            If MsgBox("Are you sure you want to disconnect?", MsgBoxStyle.YesNo, "FS-Share") = MsgBoxResult.Yes Then
                Client.Close()
                Server.Stop()
            End If
        End If
    End Sub

End Class

Compiling went good the first try immediately. Now using localhost (127.0.0.1) on the client all works fine, but when trying the hamachi IP (25.93.147.153) it throws an exception with the description: ''The requested address is not valid in its context'' (WSAEADDRNOTAVAIL). I already found out the exception was thrown when creating the winsock client, therefore it must be a winsock problem. Searching on google learned me that ''This normally results from an attempt to bind to an address that is not valid for the local machine.''. I have continued searching for the answer, tried some things myself, but nothing seems to work.... Anyone here who can help out please? I really don't know more what to do. :sick:

Thanks,
Daniël

VS 2010 Website login with WebBrowser and VB.Net 2010

$
0
0
I am converting an old Access database application over to VB.Net and have run into an issue that I need some help with. In the Access (VBA) application I can automatically login to various websites, but I can't get this to work in VB.Net. In the VB.Net code I am using a WebBrowser to navigate to a website.

Here is the my old VBA code (that works like a charm):

Code:

  Set objIE = CreateObject("InternetExplorer.Application")

  StatusBar "Opening the login window, please wait..."
  objIE.navigate (strURL)
  Do While objIE.busy
    '...wait for IE to load page
  Loop
 
  Set objHTMLDoc = objIE.Document
   
  '...wait until the key node is visible
  flgOK = False: lngStart = Timer
  Do While flgOK = False
    For Each objInput In objHTMLDoc.all.tags("INPUT")
      Debug.Print objInput.nodeName, objInput.Name, objInput.Value
      If objInput.Value = "User Name" Then
        flgOK = True
        Exit For
      End If
    Next objInput
    If (Timer - lngStart) > 15 Then Exit Do  '...quit after 15 seconds if search text hasn't been found
  Loop

  '...complete site login information
  StatusBar "Completing login procedure, please wait..."
  If flgOK = True Then
    For Each objInput In objHTMLDoc.all.tags("INPUT")
      If objInput.Name = "vb_login_username" Then
        objInput.Value = strUN
      ElseIf objInput.Name = "vb_login_password" Then
        objInput.Value = strPW
      ElseIf objInput.Value = "Log in" Then
        objInput.Click
        MsgBox "Login complete.", vbOKOnly + vbInformation
        objIE.Visible = True
        Exit For
      End If
    Next objInput
  Else
    MsgBox "Cannot locate key input node.", vbOKOnly + vbCritical
  End If

Here is the my VB.Net code (that I'm having trouble with):

Code:

            wbc.ScriptErrorsSuppressed = True
            wbc.Navigate(strURL)
            timer = Stopwatch.StartNew
            flgTimedOut = False
            Do Until wbc.ReadyState = WebBrowserReadyState.Complete
                If timer.Elapsed.Seconds > intTimeOut Then
                    flgTimedOut = True
                    Exit Do
                End If
                Application.DoEvents()
            Loop

            If (wbc.Document IsNot Nothing) Then

                wbc.Document.GetElementById("navbar_username").SetAttribute("Value", strUN)
                wbc.Document.GetElementById("navbar_password").SetAttribute("Value", strPW)

                'the "Log in" button does not have an ID, so find it by its TabIndex and OuterHTML values
                For i As Integer = 0 To wbc.Document.GetElementsByTagName("Input").Count
                    With wbc.Document.GetElementsByTagName("Input").Item(i)
                        Debug.WriteLine("Input #" & i & ": " & .Name & ", TabIndex = " & .TabIndex)
                        Debug.WriteLine(.OuterHtml)
                        If .TabIndex = 104 And InStr(.OuterHtml, "Enter your username and password") <> 0 Then
                            .InvokeMember("click")
                            wbc.Visible = True
                            If Not flgSilent Then
                                MessageBox.Show("Operation complete (" & timer.Elapsed.ToString("hh\:mm\:ss") & ").", _
                                                "VBForums Login", MessageBoxButtons.OK, MessageBoxIcon.Information)
                            End If
                            Exit For
                        End If
                    End With
                Next

            Else
                MessageBox.Show("Browser navigation did not complete in the alloted time (" & intTimeOut.ToString & _
                                If(intTimeOut = 1, " second", " seconds") & ").", "VBForums Login", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End If '(wbc.Document IsNot Nothing)

When I single-step through the code I can see that the "strUN" and "strPW" values are being assigned to the navbar_username and navbar_password elements and the InvokeMember("click") is happening. The "Operation complete" MessageBox appears and there are no errors raised. Having said that, the webpage never appears. The Windows Task Manager never shows an instance of Internet Explorer (iexplore.exe) in its Processes tab page.

I'm stumped. Can anyone give me some advice?

VS 2012 DataGridView Combobox Control

$
0
0
Hi guys,

Just wondering if there was a way of populating a DataGridView control during runtime so that in one column there could be a few rows set to type string followed by a combobox control cell all in the same column?

Thanks
Viewing all 27389 articles
Browse latest View live


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