Creating a Pop-Up Using ASP.NET VB

I have searched for a way to create a simple popup on my project. Something that is scalable and reusable. I found the answer and I do not know why I never thought of this. It consists of a little five line function. It can probably be done in C# as well.  I just haven’t taken the time to convert it over.  Well here it is.  All you have to do is pass in the page, the message, and a key.

 

CreateMessageAlert(page, message, “keyname”)

 

Message has to be type of string:

Dim message As String

 

Below is the code to implement the above call:

 

Public Shared Sub CreateMessageAlert(ByRef aspxPage As System.Web.UI.Page, _

                           ByVal strMessage As String, ByVal strKey As String)

        Dim strScript As String = “<script language=JavaScript>alert(‘” _

                                            & strMessage & “‘)</script>

        If (Not aspxPage.IsStartupScriptRegistered(strKey)) Then

            aspxPage.RegisterStartupScript(strKey, strScript)

        End If

    End Sub

 

That is it. Not too bad. Pretty easy stuff. Hope this helped.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

  

Using Classes in ASP.NET VB

I have created a web application that introduced me to something I haven’t really used before, classes.  They are a great thing.  This may be a 101 style post but I find it very interesting.  What I have done is create a class of user. Inside the user.vb class I have all the methods/functions that has to do with the user.  I have things like a function to find the user name, another to find user ID, and yet another to find the user roles. To use it all you have to do is create an instance of that class and you can call the methods directly on the caller page. For instance my class is named user.vb. To use it you have to reference it. This is how I reference it:

 

Dim iUser As New User

 

That’s it! Then to use the methods:

 

iUser.methodname()

 

How easy is that?  I also have a sqlMethod.vb which houses all my sql methods used throughout my web application.  I even use it in the User class. Again, the same way whether its in a class or another page is to use the:

 

Dim iSQL As New sqlMethods

 

And then you guessed it, to use any method just reference it like:

 

iSQL.methodname()

 

You can also pass in variables if you need to:

 

iSQL.Methodname(var1, var2)

 

One thing to remember is that the call has to be set to a variable. You have to have:

 

Dim roles As String

Roles = iSQL.roles(userID)

 

To create the class, if your using Visual Studio, you just have to right click on the project name and choose add new item and choose class, name it, and your good to go to use one. Make sure you Import anything that is needed at the top of the class. Below is a real world example of how I use it.

 

Here is my User.vb code:

 

Dim iSQL As New sqlMethods

Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String

        Dim userID As String

        userID = iSQL.GetUserID(userlogin, userpassword).ToString

        Return userID

    End Function

 

Here is my sqlMethods.vb Code:

 

Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String

        Dim mySQLString As String = “SELECT tblUser.userID FROM tblUser WHERE tblUser.userLogin = ‘” & userlogin & “‘ AND tblUser.userPassword = ‘” & userpassword & “‘”

        Dim myCommand As New SqlCommand(mySQLString, dsn)

        Dim userID As String

        Try

            dsn.Open()

            userID = Convert.ToString(myCommand.ExecuteScalar())

            If userID = “” Then

                Return 0

            Else

               Return userID

            End If

        Catch ex As Exception

            ‘Something went wrong

            dsn.Close()

            Throw ex

        Finally

            ‘Cleanup

            dsn.Close()

        End Try

    End Function

 

Hope this helped.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

Working with a Database in ASP.NET VB

I just realized I added code on the blog for working with databases in C# but not for VB.  This will be the missing post of one way in which you can use Visual Basic. Enjoy!

Imports System.Data

Imports System.Data.SqlClient

Dim cs As String = “Data Source=.\SQLEXPRESS;” + _

Dim cs As String = “Initial Catalog=NamesDB;” + _

Dim cs As String = “Integrated Security=True;”

Using con As New SqlConnection(cs)

con.Open()

‘ insert a record

sql = “INSERT INTO Names(Name) VALUES(@Name)”

Dim cmd1 As New SqlCommand(sql, con)

cmd1.Parameters.Add(“@Name”, SqlDbType.NVarChar, 100)

cmd1.Parameters(“@Name”).Value = “Bob”

cmd1.ExecuteNonQuery()

‘ insert a second record

cmd1.Parameters(“@Name”).Value = “David”

cmd1.ExecuteNonQuery()

‘ read records

sql = “SELECT * FROM Names”

Dim cmd2 As New SqlCommand(sql, con)

Using r As SqlDataReader = cmd2.ExecuteReader()

Dim iName As Integer = r.GetOrdinal(“Name”)

Do While r.Read()

If r.IsDbNull(iName) Then

Console.WriteLine(“Null”)

Else

Console.WriteLine(r.GetString(iName))

End If

Loop

End Using

‘ read a single value

sql = “SELECT TOP 1 Name FROM Names”

Dim cmd3 As New SqlCommand(sql, con)

Console.WriteLine(cmd3.ExecuteScalar())

End Using

 

(This post was done with the help of LearnVisualStudio.net. Thanks!)

In a future post I will be sure to add a post about how to use stored procedures! Hope this helps you.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

 

Page.IsPostback is Sneaky

   I had an issue yesterday with a dropdown on a form. I was trying to post the values to a new form.  All the values would post fine except this one dropdown.  I was racking my brain.  What was happening is everytime I submitted the form, the value of the dropdown (varname.SelectedItem.Value) would be item[0] no matter what I choose!?  This was driving me crazy because all the other form variables were passing just fine. I even had another dropdown that was posting fine.  This one was giving me a problem.  What was the difference you may ask?  The only difference was that the dropdown that was not passing correctly was dynamically populated by a databind.  Well, it turns out, which now makes sense, is that when the page posts back, the original value is sent. This happens because the page load function runs first on post back. Hence the default value being posted. What you have to do is this;

 

If Not Page.IsPostBack Then

   varname.DataSource = DataTable

   varname.DataTextField = “value

   varname.DataValueField = “value

   varname.DataBind()

End If

 

Adding these two lines of code around my databind worked wonders. It’s the small things that count. Keep your eyes open and as always, if there are any questions or suggestions, they are welcome. Thank you.

Working With Dates and Times Using ASP.NET VB

I know we have all have to use dates at some time or another.  I came across this posting and thought I would list it here for you.  Hope it helps.

Dim now As Date = Date.Now ‘ date and time

Dim today As Date = Date.Today ‘ just the date

Dim tomorrow As Date = today.AddDays(1)

Dim yesterday As Date = today.AddDays(-1)

‘ use parse functions to convert from strings

Dim vb1 As Date = Date.Parse(“1991-05-01″)

‘ use culture info to parse dates in regional formats

Dim gb As New CultureInfo(“en-GB”)

vb1 = Date.Parse(“01-05-1991″, gb.DateTimeFormat)

‘ format dates as strings

vb1.ToLongDateString() ‘ Wednesday, May 01, 1991

vb1.ToShortDateString() ‘ 5/1/1991

vb1.ToLongTimeString() ‘ 12:00:00 AM

vb1.ToShortTimeString() ‘ 12:00 AM

vb1.ToString(“u”) ‘ 1991-05-01 00:00:00Z

vb1.ToString(“yyyy-MM-dd”) ‘ 1991-05-01

‘ TimeSpan represents differnce between two dates

Dim time As TimeSpan = tomorrow – today

Dim days As Integer = time.Days

Dim hours As Integer = time.Hours

Dim minutes As Integer = time.Minutes

Dim seconds As Integer = time.Seconds

Dim milliseconds As Integer = time.Milliseconds

‘ Add time using other timespan instances

time.Add(New TimeSpan(days, hours, minutes, seconds,

milliseconds))

‘ or

time += New TimeSpan(days, hours, minutes, seconds,

milliseconds)

‘ use a timespan to add time to a date

today.Add(time)

‘ or

today += time

‘ timespan represented as Days.Hours:Minutes:Seconds:

‘ Subseconds

time = TimeSpan.Parse(“1.2:3:4:5″)

‘ or

If TimeSpan.TryParse(Console.ReadLine(), time) Then

Console.WriteLine(time)

End If

 

As always, if there are any questions or suggestions, they are welcome. Thank you.