VB.net If then Else with a list of strings


In SQL server you can do an easy exclude or include list by using an in statement.
So you can do:

Select * from someTable where somecolumn in (‘somestring1’, ‘somestring2’, ‘somestring3’, ‘somestring4’)

So you only get records where the contents of somecolumn are in the specified list of strings.
I wanted to do something similiar in VB.net.
You can use an if then or statement but it can get messy.

If someStringToCheck = “somestring1” or someStringToCheck = “somestring2” or someStringToCheck = “somestring3” or someStringToCheck = “somestring4” then
…Do something blah blah…
end if

This works but what if you have a list of 20 strings you want to check for?
Through some internet searching I found this post on stackoverflow.com and came up with the following:

Dim someList = New List(Of String) From {“somestring1”, “somestring2”, “somestring3”, “somestring4”}
If someList.Contains(someStringToCheck) Then
…Do something blah blah…
…Do something else blah blah…
end if

It seems kind of backwards but it takes your list of strings and determines if the string you fed it is in that list.  If so do something or if not then do something else.

  • Camera: Venue 8 7840
  • Taken: 7 April, 2015
  • Aperture: ƒ/2.4
  • Focal length: 2.94mm
  • ISO: 37
  • Shutter speed: 1/85s
  • Title: Jpeg

How to sort DirectoryInfo.Getfiles array

I have an Intranet page that looks at a folder of files and lists them out.  It uses io.directoryinfo.getfiles to get the list of files but there wasn’t anyway to control the sorting.  By default it was sorting ascending but i wanted it reversed.  Here’s what I had at first:

Dim di As New IO.DirectoryInfo(Server.MapPath(“FolderofFiles”))
Dim aryFi As IO.FileInfo() = di.GetFiles(“*.pdf”)
Dim fi As IO.FileInfo
For Each fi In aryFi
..blah blah loop

I tried to add Array.Sort(aryFi) but that resulted in an error:
“At least one object must implement IComparable.”

So after some internet searching I came up with the following based on a post on stackoverflow.com

First you have to create an IComparer class:

Private Class FileNameComparer
Implements System.Collections.IComparer
Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)
Dim Filename1 As String = FileInfo1.FullName
Dim Filename2 As String = FileInfo2.FullName
If Filename1 > Filename2 Then Return -1
If Filename1 < Filename2 Then Return 1
Return 0
End Function
End Class

Then use the comparer to sort:

Dim di As New IO.DirectoryInfo(Server.MapPath(“Folderoffiles”))
Dim aryFi As IO.FileInfo() = di.GetFiles(“*.pdf”)
Dim comparer As IComparer = New FileNameComparer()
Array.Sort(aryFi, comparer)
Dim fi As IO.FileInfo
For Each fi In aryFi
..blah blah loop

The comparer I tweaked sorts the files by their filename in a descending order.  You can reverse the Return -1 and Return 1 to get them into ascending order.
Also, if you would like to sort the files by creation date you could use this comparer:

Private Class DateComparer
Implements System.Collections.IComparer
Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)
Dim Date1 As DateTime = FileInfo1.CreationTime
Dim Date2 As DateTime = FileInfo2.CreationTime
If Date1 > Date2 Then Return 1
If Date1 < Date2 Then Return -1
Return 0
End Function
End Class

Then you’d change:

Dim comparer As IComparer = New FileNameComparer()
Dim comparer As IComparer = New DateComparer()

ASP.net Gridview error with Delete button – Must declare the scalar variable


I have a Gridview on an ASP.net page.  I added the delete command to the SQL data source and told the gridview to “Enable Deleting.”

When the delete button is clicked I get an error – “Must declare the scalar variable @oid”.
OID in my case is the primary key of the table I’m wanting to be able to delete from.


The fix is very easy.  You want to go to the source view of the page where the gridview is at.
Add: DataKeyNames=”oid” to the asp:gridview code.  You need to change oid to the column name you are using to identify the record to delete.


Now you should be able to delete to your heart’s content.

Force an image to load from server (PHP or ASP.NET)


I ran across a need to make sure an image on a webpage loaded from the server on each load of the page.  This was accomplished by loading the images with a random number as a parameter.
So it ended up looking like:  <img src=”http://www.website.com/images/1.png?rndNum=2204>

In PHP this was done by adding:  ?<?php echo rand(1000,7000)?> to the image source.

In asp.net (VB):  Using an asp:image with id =”Image1″ on the page.
VB code behind:
If Not Me.IsPostBack Then
Dim randImgNum As Integer
randImgNum = RandomNumber(1000,7000)
Me.Image1.ImageUrl = “http://www.website.com/1.png?rndNum=” & randImgNun
end if



VB.net get size of folder and or a drive

You can use this function to return the size of a specific folder:

Public Function FldrSize(ByVal dPath As String)
Dim size As Long = 0
For Each foundFile As String In My.Computer.FileSystem.GetFiles(dPath, FileIO.SearchOption.SearchAllSubDirectories, “*.*”)
Dim fInfo As New FileInfo(foundFile)
size += fInfo.Length
Return size
End Function

This returns the number of bytes in the folder.  I then feed that result to code found here to view that as megabtyes or gigabytes.

This function returns the total size of a drive and the free space of the specified drive:

Private Function GetSize(ByVal drive As String)
Dim parameter As String = “win32_logicaldisk.deviceid=””” + drive + “:”””
Dim diskSize As New ManagementObject(parameter)
Dim detailsString As String = “”
detailsString = “Disk Space in ” + drive + ” is :” & diskSize(“Size”).ToString
detailsString = detailsString & vbCrLf & “<br>Free space in ” + drive + ” is :” & diskSize(“FreeSpace”).ToString
Return detailsString
End Function

Again, this returns the bytes and I use code found here to convert that to megabytes or gigabytes.


ASP.net – Using enter key in a textbox to trigger a button event as well as set focus and select text in the text box

Ok, that’s probably the longest post title I’ve used yet.
Here’s what I’m working with: a form with a textbox a button and a listbox.  Users enter text into the textbox and hit the button to search for information which is returned into the listbox.
The first issue was I don’t want to have to click the search button to start the search.  I wanted to be able to just hit enter after typing text.  The button triggers vb code behind the page to do the search.

So I found adding the following to the Page_Load sub-routine allowed me to hit enter in the textbox which triggers the button code:

txtSearch.Attributes.Add(“onkeypress”, “return clickButton(event,'” + btnSearch.ClientID + “‘)”)

Replace txtSearch with the id of your textbox and replace btnSearch with the id of your button.

Next, I wanted the text in the textbox to be highlighted/selected after performing a search so you could turn around and type something else and do another search without touching the mouse.
This is accomplished by adding the following to the Page_Load sub-routine:

txtSearch.Attributes.Add(“onfocus”, “JavaScript:document.getElementById(‘” + txtSearch.ClientID + “‘).select();”)

Replace txtSearch with the id of your textbox.

Note:  Sometimes when you copy and paste code like that above the quotes and or apostrophes can get funky and need to be corrected.

Date and 24 hour time batch file variables

I’ve lately been using batch files more and more to do backups and other things.
One of the things that’s given me troubles is using dates and times to add to folders or file names to help with organizing.
What I wanted to end up with is something like 20110211_185530.zip.  The first part is the year then month then date followed by an underscore the hour then minutes then seconds.

For the impatient out there here is the final code I use to get this date and time stamp:
I’ll explain why it looks more complicated than you (and I) might have thought it should be afterwards.

set hh=%time:~-11,2%
set /a hh=%hh%+100
set hh=%hh:~1%
Set dateseed=%date:~10,4%%date:~4,2%%date:~7,2%_%hh%%time:~3,2%%time:~6,2%
echo %dateseed%

The %Time% variable in a batch file will give you a time like 18:55:30.32
The  %Date% variable will give you  “Fri 02/11/2010”.

Since I’m using this to create file and folder names you can’t have slashes and colons etc. mixed in there.
So, being a VB programmer I started out thinking I could use something like the mid function to take the date and time apart and then put it back together in the string I wanted.

I found that you can take just a part of the %date% variable by doing the following: %date~10,4%
This takes the %date% variable starts at the first character after the 10th and grabs 4 characters.
Cool, so you end up %date~10,4% = 2011 (unless you go back in time to last year or forward to next year in which it will be something else and if you can do that then you probably aren’t reading this.)
You can add a negative sign before the first number and it will go from right to left instead of left to right when setting character position.

So with %date:~10,4%%date:~4,2%%date:~7,2% = 20110211 (because today is 02/11/2011).
Take the time and you get %time:~-11,2%%time:~3,2%%time:~6,2% = 191551 (because it’s 7:15 pm at 51 seconds)

Based on these then I came up with:
Set dateseed=%date:~10,4%%date:~4,2%%date:~7,2%_%time:~-11,2%%time:~3,2%%time:~6,2%
echo %dateseed%
This returns: 20110211_191655 and was exactly what I wanted.  So, why is the final code I gave you above so much more complicated?  I started using the above code and had problems when it went to make a folder and the time was like 2 am.
The problem is the hour part of the %time% variable doesn’t return a two digit hour like at 2 am.  The %time~-11,2% would return a 2 with a space before it breaking the whole thing.

So, the first lines in the above code compensates for this by taking the hour and adding 100 to it and then pulling out the last 2 characters of what remains.  So at 2 am you end up with 102, take the last two characters and you get 02.  This makes for a more reliable method of making folders and file names using the %date% and %time% variables.

There might be a much better, shorter way to accomplish this but I couldn’t find it so here’s the final code:
(until someone smarter than me tells me how silly I am for doing it this way and gives me something better)

set hh=%time:~-11,2%
set /a hh=%hh%+100
set hh=%hh:~1%
Set dateseed=%date:~10,4%%date:~4,2%%date:~7,2%_%hh%%time:~3,2%%time:~6,2%
echo %dateseed%

Set the value and text of a bulleted list using Hyperlink mode from VB.NET code behind

I love the internet.  All of the answers to life are on the internet if you take enough time to look.
Not only are the answers to life’s big questions out there, like what happens when I die?
But also the answers to things like how on earth do I set the value (what’s not seen and in my case was a URL) and the text (what’s seen) of a bulleted list that is being displayed in Hyperlink mode?

It took a little while and I finally found something that looked like the answer but it was in C#, which I know pretty much nothing about.
But there’s this handy website that can convert C# code to VB.NET.

So here it is (from experts-exchange.com, another valuable website):

Dim objListItem As New ListItem()
For i As Integer = 0 To 9
objListItem.Value = YourURLStringValueHere
objListItem.Text = YourDisplayTextStringValueHere
BulletedList1.DisplayMode = BulletedListDisplayMode.HyperLink

The loop is just there for explanation purposes.  In my case the loop was a set of data from a SQL connection.

Whew, ok I’m going to bed now that this is figured out.

ASP.Net Popup window from a hyperlink within Gridview results that passes 2 parameters

I spent a fair amount of time nailing this one down so I figured I’d better record it for future reference.

From within your gridview section add your columns and change one of the columns to a template then you can manipulate what shows up for that column.

<asp:HyperLink ID=”HyperLink1″ runat=”server” Font-Underline=”True”
NavigateUrl=<%# String.Format(“javascript:void(window.open(‘http://intranet/somepage.aspx?parameter1=” & Eval(“gridviewColumnName1”) & “&parameter2=” & Eval(“gridviewColumnName2”) &  
“‘,’_blank’,’width=750,height=700,toolbar=no,status=yes,scrollbars=yes,resizable=no’))”, Eval(“gridviewColumnName1”)) %>
Text='<%# Bind(“gridviewColumnName1”) %>’></asp:HyperLink>

What you end up with is a hyperlink that looks something like this:


So the hyperlink will popup a window and take you to your specified page and passes 2 parameters to the page that can then be acted upon.

Hopefully this makes sense.  It does to me right now, but who knows when I come back to it later!  :)

Note:  many times when you copy and paste this sort of code into your environment you’ll have to change the apostrophes because they get replaced with a backwards apostrophe which will cause problems.