1 . Check if TcpClient was not called using vb.net?

Answer :

IsNot. One word:

If clientTest IsNot Nothing ...

Alternatively, you can write this:

If Not (clientTest Is Nothing) ...

Nothing for reference types is a special value, and negating it directly via a logical Not doesn't help you. A logical Not of an unknown value is still an unknown value.

Instead, you want either the IsNot logical inverse for the Is operator, or just the Is operator where you place the logical Not to negate the entire boolean expression.

Leave a Comment

1 . Setting the namespace of a WinForms UserControl in VB.NET?

Answer :
Imports System.ComponentModel

Namespace Controls
   Friend Class FloatingSearchForm

      'Your code goes here...

   End Class
End Namespace

You will not be able to specify that the controls are in a different root namespace than that specified for the project they are a part of. VB will simply append whatever you specify for the namespace to the namespace specified in the project properties window. So, if your entire project is "AcmeCorporation.WidgetProgram" and you add "Namespace Controls" to the top of a control file, the control will be in the namespace "AcmeCorporation.WidgetProgram.Controls". It is not possible to make the control appear in the "AcmeCorporation.SomeOtherProgram.Controls" namespace.

Also note that if you are using the designer to edit your controls, you need to add the Namespace keyword to the hidden partial class created by the designer. Click the "Show All Files" button in the solution explorer, then click the expand arrow next to your control. You should see a "*.Designer.vb" file listed. Add the Namespace to that file as well. The designer will respect this modification, and your project should now compile without error. Obviously, the namespace specified in the designer partial class must be the same one as that specified in your class file! For the above example:

Namespace Controls
   <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
   Partial Class FloatingSearchForm

      'Designer generated code

   End Class
End Namespace

2 . Marking A Class Static in VB.NET?

Answer :

Module == static class

If you just want a class that you can't inherit, use a NotInheritable class. But it won't be static/Shared. You could mark all the methods, properties, and members as Shared, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.

If you really want the vb.net equivalent to a C# static class, use a Module. It can't be inherited and all members, properties, and methods are static/shared


Answer :
    Dim fr As System.Net.HttpWebRequest
    Dim targetURI As New Uri("http://whatever.you.want.to.get/file.html")         

    fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
    If (fr.GetResponse().ContentLength > 0) Then
        Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
    End If   
Catch ex As System.Net.WebException
   'Error in accessing the resource, handle it
End Try

A second option is to use the WebClient class, this provides an easier to use interface for downloading web resources but is not as flexible as HttpWebRequest:

Sub Main()
    'Address of URL
    Dim URL As String = http://whatever.com
    ' Get HTML data
    Dim client As WebClient = New WebClient()
    Dim data As Stream = client.OpenRead(URL)
    Dim reader As StreamReader = New StreamReader(data)
    Dim str As String = ""
    str = reader.ReadLine()
    Do While str.Length > 0
        str = reader.ReadLine()
End Sub

4 . How do I set the thickness of a line in VB.NET?

Answer :

Use the pen's Width property.

aPen.Width = 10.0F

5 . How do I kill a process using Vb.NET or C#?

Answer :
foreach ( Process process in Process.GetProcessesByName( "winword.exe" ) )

6 . Why doesn't VB.NET 9 have Automatic Properties like C# 3?

Answer :

C# and VB.NET don't exactly line up on new features in their first versions. Usually, by the next version C# catches up with some VB.NET features and vice versa. I kind of like literal XML from VB.NET, and hoping they add that to C#.

7 . How do I escape from a Snippet? (Vb.Net)

Answer :

Meanwhile, in case anyone cares, I created an additional replacement field ($Enter$) at the end of my custom snippet. This allows me to [tab] through the fields and then type [DownArrow] [Enter] when I reach the end of the list.

Something like....

private _$PropertyName$ As $PropertyType$
Public WriteOnly Property $PropertyName$() As $PropertyType$
     Set(ByVal value as $PropertyType$)
          _$PropertyName$ = value
     End Set
End Property $Enter$

8 . How to populate datagridview with already defined columns in VB.Net?

Answer :

Instead of doing things like this, you can make alias of the column names which you want to show in your grid like this :

select col1 as [Column 1], col2 as [Column 2], col3 from offerte.Offerteinhoud ...

And then if you don't want to show column col3, you can hide it using the below code :

DataGridView1.Columns("col3").Visible = False

9 . linq groupby without time field vb.net?

Answer :

Normally your would use the DateTime.Date property, but EF6 does not support it and requires using DbFunctions.TruncateTime method for tat purpose.

Also, VB.NET does not demand using anonymous type (although I'm pretty sure there is way to specify the anonymous type member name). When you group by a single field like in your case, you could use simply the following (as shown in Group By VB.NET example):

.GroupBy(Function(GroupTime) DbFunctions.TruncateTime(GroupTime.Scheduled_Start))

10 . Yes/No message box always returns yes - VB.Net?

Answer :

The MsgBox() method is returning MsgboxResult Enumeration, check the value that the method returns:

Public Sub MsgBoxExample()
    Dim result As MsgBoxResult = Nothing
    Dim chc As Integer

    result = MsgBox("click something...", vbYesNo, "example")
    If result = MsgBoxResult.Yes Then
        chc = 1
    ElseIf result = MsgBoxResult.No Then
        chc = 0
    End If
End Sub

11 . Checksum calculation in vb.net?

Answer :

Need to track the overflow and modulo separately, if you want to add them. That's not what your 1st line 'Checksum = INV (data byte 1 ⊕ data byte 2 ⊕ ... ⊕ data byte 8)' indicates though - are you sure? Code would be like this (gives &H33):

Dim sum As Integer = 0
Dim bytes() As Byte = {&H22, &H22, &HAA, &HAA, &H55, &H55, &H44, &H44}
For i As Integer = 0 To bytes.Length - 1
    sum += bytes(i)
Dim overflow = sum \ 256
Dim modulo = sum Mod 256
sum = Not (CByte((overflow + modulo) Mod 256))

12 . How to wrap long word with TextRenderer DrawText in vb.net?

Answer :

Just to add some implementation details that can be used to evaluate the differences between TextRenderer .DrawText() method and PaintEventArgs.Graphics .DrawString() method.

Clicking on the Form, the two methods show their differences in measuring and rendering the text.

Dim sText As String() =
         New String() {


In the Form's Click() event, draw sText lines, measuring their Width and Height using TextRenderer.MeasureText() and print them with TextRenderer.DrawText()

  Private Sub Form1_Click(sender As Object, e As EventArgs) Handles Me.Click

     Dim _RelPositionY As Integer = 0
     Dim _LineSpacing As Single = 0.5
     Dim _ParagraphSpacing As Integer = CInt(Me.Font.Height * _LineSpacing)

     Dim _Flags As TextFormatFlags = TextFormatFlags.Top Or
                                     TextFormatFlags.WordBreak Or 

     For x = 0 To sText.Length - 1
         Dim _size As Size = TextRenderer.MeasureText(
                             Me.CreateGraphics(), sText(x), Me.Font,
                             New Size(Me.ClientSize.Width, Me.Height), _Flags)

         TextRenderer.DrawText(Me.CreateGraphics(), sText(x), Me.Font,
                               New Rectangle(0, _RelPositionY, _size.Width, _size.Height),

         _RelPositionY += _size.Height + _ParagraphSpacing

  End Sub

In the Form's Paint() event, draw sText lines, measuring their Width and Height using .Graphics.MeasureString() and print them with .Graphics.DrawString()

Note that the text boxed size in TextRenderer is relative to the Form.ClientSize, while in Graphics is relative to the Form's full Width.

  Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
     Dim _RelPositionY As Single = 0
     Dim _LineSpacing As Single = 0.5
     Dim _ParagraphSpacing As Single = CSng(Me.Font.Height) * _LineSpacing

     Dim _Flags As StringFormatFlags = StringFormatFlags.LineLimit Or

     For x = 0 To sText.Length - 1
        Dim _sizeF As SizeF = e.Graphics.MeasureString(sText(x), Me.Font,
                              New SizeF(CSng(Me.Width), CSng(Me.Height)),
                              New StringFormat(_Flags))

        e.Graphics.DrawString(sText(x), Me.Font,
                              New SolidBrush(Me.ForeColor),
                              New RectangleF(0, _RelPositionY, _sizeF.Width, _sizeF.Height))

         _RelPositionY += _sizeF.Height + _ParagraphSpacing

  End Sub

13 . Searching in Datagridview using textbox VB.net?

Answer :

After binding your dataset to the datagrid, you can try the following code snippet:

Dim dv As DataView

dv = New DataView(yourDataset.Tables(0), "YourDataColumnName= '" & Me.txtSearchBox.Text & "' ", "YourDataColumnName", DataViewRowState.CurrentRows)
Me.YourDataGridView.DataSource = dv

14 . Vb.net, replace any number at the end of a string with a placeholder?

Answer :

You could use a Regex for this.

Dim str As String = "some123variable9480395"
Dim pattern As String = "\d+$"
Dim replacement As String = "%placeholder%"
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement)

15 . Exporting data into Excel based on a predefined template using VB.net?

Answer :
'Opens Excel and stores a reference to Excel process
xlTmp = New Excel.Application 

'Opens the excel file with path '_fileName'
_xlTmp.Workbooks.Open(_fileName, , True, , , , , , , True)

'Stores a reference to Sheet named "SHEET1"
Dim xlNewSheet = CType(_xlTmp.Worksheets.Item("SHEET1"), Excel.Worksheet)

'Copies the refered sheet to sheet named "SHEET2" - replacing it                                                                      
xlNewSheet.Copy(CType(_xlTmp.Worksheets("SHEET2"), Excel.Worksheet))

'Reference to the copied sheet
xlNewSheet = CType(_xlTmp.Worksheets.Item("SHEET1 (2)"), Excel.Worksheet)

However, if you use Excel COM you should code in a different way, so you can dispose all objects "referencing something" in Excel. You will also get exceptions if the filename or sheets with given names are not found.