.net.devcity.weekly ---

Advertisement

Advertisement

The newsletter is compiled by DevCity.NET NewsMasters XTab and Mike McIntyre

Advertisement

Table Of Content:

Advertisement

by Mike McIntyre

Setting the location of a form seems such a simple thing, but as DevCity Leader Mike McIntyre shows you, there are more combinations and points to consider than you may at first realise.

Opening and positioning forms on a user's screen is a common task for VB.NET Windows Forms programmers. This article provides VB.NET newies an introduction to this programming task. For VB.OLD programmers the article includes explanations of how positioning forms has changed from VB6 to VB.NET.

The Form properties StartLocation and Location control where the Form will be located when it is first opened. Both properties can be set at design time through the Form property grid. These properties may also be set programmatically at runtime through code added to the form's initialization block or to its Load handler.

StartLocation Property

StartLocation is a .NET enumeration that represents the five possible start positions for a Windows Form form.

  • CenterParent : The form is centered within the bounds of its parent form.
  • CenterScreen: The form is centered on the current display, and has the dimensions specified in the form's size.
  • Manual: The location and size of the form will determine its starting position.
  • WindowsDefaultBounds: The form is positioned at the Windows default location and has the bounds determined by Windows default.
  • WindowsDefaultLocation: The form is positioned at the Windows default location and has the dimensions specified in the form's size.

Location Property

Location is the position of the top left corner of a Form. A form's Location property is a point consisting of x- and y-coordinates that defines a point on the computer screen.

Using StartLocation and Location

VB.NET uses a combination of StatupLocation and Location to position a form when it is first opened. Shown next are four examples that demonstrate how different combinations of StartLocation and Location affect the start position and sometimes the size of a form when it is first opened.

Example One - Intial Settings

StartLocation = Manual
Location = 0,0
Size = 200,200

Location and Size When Form Opens
Location: {X=0,Y=0}
Size: {Width=200, Height=200}

Example Two - Initial Settings

StartLocation = Center
Location = 0,0
Size = 200,200

Location and Size When Form Opens
Location: {X=412,Y=267}
Size: {Width=200, Height=200}

Example Three - Initial Settings

StartLocation = WindowsDefaultBounds
Location = 0,0
Size = 200,200

Location and Size When Form Opens
Location: {X=88,Y=116}
Size: {Width=768, Height=527}

Example Four - Initial Settings

StartLocation = WidowsDefaultLocation
Location = 0,0
Size = 200,200

Location and Size When Form Opens
Location: {X=22,Y=29}
Size: {Width=200, Height=200}

Note:

Different Combinations; Different Results

Though the Location and Size properties of the form in all examples above are set the same at design time, the actual location and size of the form when it opens varies depending on what StartLocation enumerator is used.

Because screen size and resolution can vary from system to system, WindowsDefaultLocation is used by most Windows applications. This tells the operating system to use the best location for the form at startup, based on the current hardware. If your application will run on systems with different screen sizes, resolutions, and/or multiple monitors consider using WindowsDefaultLocation as the StartPosition for your main form.

VB.NET vs VB6

In VB6, the initial screen location for a form could be specified by setting the Left and Top properties of a form. Left and Top are obsolete in VB.NET. Instead Location represents the X-Y (Left-Top) coordinate of the upper left corner of a form.

In VB6 one could set the StartUpPosition property to allow Windows to automatically set a location for the form when it first opened. The default setting was Manual, meaning that the Left and Top properties took precedence. In VB.NET the StartPosition property performs the same function. The default setting is now WindowsDefaultLocation, meaning that the Location property is ignored.

For more information about setting the screen location of Windows Forms click here.

Diary of a .NET Newbie: Running in Blinkers

Do any of us really know just how much functionality, help and assistance is built into Visual Studio? I'm sure that I don't. But I do know that it's one heck of a lot.

Funny thing is, though, that I suspect many of us might have started off like I did. You get Visual Studio installed, you've got a bit of previous experience of VB.Old, and so you just can't wait to get stuck into writing some little app just to get the feel of things. Then you find yourself temporarily stuck, so you go off somewhere (hopefully to VBCity!) and find the answer before you get back on with the coding again.

And so it goes on. Until suddenly, weeks or even months down the line, you realise that maybe you're not working as efficiently as you could be, should be. You always knew that there are a zillion little knick-knacks provided in Visual Studio, but somehow you never really got round to finding out more about them or using them.

Here's a few things that I missed first time round, but which I use quite a lot now that I've discovered them:

1. The General Tab in the ToolBox.

Forget Cut and Paste when you've got Drag and Drop! Select any chunk of code in your current project and simply drag and drop it from the Code Window on to the General Tab in the ToolBox. A copy will automatically be saved there for you for later use in this project or solution. Better yet, it will be available there for use in any other Solution that you subsequently open.

And, yes, in case you're wondering what happens when your General Tab is overflowing with code snippets you no longer need, you can delete any of them. Note that this deletes the item globally as it removes the item from the ToolBox itself, not just from your current Solution in the IDE.

2. F1 to the Full.

We all know that if you select a word in the Code Window and press the F1 key that this will automatically display an associated Help item for you (with varying degrees of accuracy, I know, but hey! dotNet's a massive subject). Did you know that if you select any control in the IDE's Form Designer window and click F1 that you'll get the relevant Help Screen for that control also? Or any component either? You did? OK.

Oh, did you know that you don't even have to be using a control to get it's Help page up with F1? You didn't? Well, I'll tell you how then. Just left click once on the control in the ToolBox and then press F1. Pretty cool, huh?

Or to get the lowdown on any particular Property of a control, just select the property name in the Property Window (NB. The Property Name at the left, or the current setting at the right - it doesn't matter which) and hit that ol' F1 key again.

3. Tooling Around with the Toolbox

And finally for today, still in the toolbox, did you know that you can sort the ToolBox items alphabetically if you don't like the default order (The MS best guess of the most popular controls)? Right click on the ToolBox Tab (eg "Windows Forms") and select the "Sort Items Alphabetically" item from the list. By the way, I haven't yet found a choice that undoes this or resets the toolbox back to that default (which can be a bit of a pain). It may be there; I just haven't found it.

Before leaving the toolbox (and the diary), it may be handy to know that you can drag and drop any of the ToolBox items within that list so that you can personalise, order and reorder the items as much as you like. As with the General Tab, the settings are saved in Visual Studio and will be available in all future Solutions as you open them up.

Hopefully some of the above might help some of us to do a little less "running in blinkers" than we have been and maybe the next project will be written, compiled and running perfectly, in the blink of an eye.

- Junior (Ged Mead aka XTab, xtab@vbcity.com)

by Mike McIntyre

The .NET Framework namespaces "SqlDB" and "OleDB" provide two specific classes that represent exceptions that may be raised when a .NET program attempts to communicate with a database. Details are returned for failed connections, SELECTS, INSERTS, UPDATES, DELETES and other failed database commands.

The two classes are the SqlException and OleDbException classes. By handling these exceptions with a Try...Catch block you can get specific details about the database exceptions that occur.

Both classes return a collection of errors. To expose all database errors returned in a SqlException or an OleDbException your code must loop through the error collection. Shown below is an example for handling an OleDbException and another for handling a SqlException. For the purposes of this article both examples create bad database connection code to force database exceptions to occur.

Example: OleDbException Handler

' Create a query string.
Dim aQuery As String = "SELECT CustomerName FROM Customers"
' Instantiate an invalid OleDbConnection
' and assign it to the myConnection variable.
Dim aConnection As New OleDbConnection _
    ("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=")
Dim aCommand As New OleDbCommand(aQuery, aConnection)
' Wrap an OleDb method (Open) in an exception handler.
Try
    ' Because an invalid OleDbConnection is used
    ' this statement will raise an OleDbException.
    aCommand.Connection.Open()
Catch ex As OleDbException
    ' Show a general message about the error.
    MessageBox.Show(ex.ToString)
    ' Loop through all OleDbException errors
    ' returned by the database.
    Dim i As Integer
    For i = 0 To ex.Errors.Count - 1
        ' Report the error details.
        Console.WriteLine("Message: " & ex.Errors(i).Message)
        Console.WriteLine("NativeError: " & ex.Errors(i).NativeError)
        Console.WriteLine("Source: " + ex.Errors(i).Source)
        Console.WriteLine("SQLState: " + ex.Errors(i).SQLState)
    Next i
End Try

Result:
Message: Could not find installable ISAM.
NativeError: -69141536
Source: Microsoft JET Database Engine
SQLState: 3170

Example: SqlException Handler

' Declare a variable of type ConnectionString named aConnectionString.
' Assign a connection string to a non-existent server to
' the aConnectionString to force a SqlException.
Dim aConnectionString As String = _
    "user id=sa;password=;database=northwind;server=badserver"
Dim aConnection As New SqlConnection(aConnectionString)
Me.Cursor = Cursors.WaitCursor
' Wrap a SqlDb method (Open) in an exception handler.
Try
    aConnection.Open()
Catch ex As System.Data.SqlClient.SqlException
    Console.WriteLine(ex.Message)
    ' Loop through all errors returned.
    Dim i As Integer

    For i = 0 To ex.Errors.Count - 1
        ' Report error details.
        Console.WriteLine("Class: ", ex.Errors.Item(i).Class.ToString)
        Console.WriteLine("Error #: " & ex.Errors.Item(i).Number.ToString)
        Console.WriteLine("Error Message: " & ex.Errors.Item(i).Message)
        Console.WriteLine("Line Number: " & _
                          ex.Errors.Item(i).LineNumber.ToString)
        Console.WriteLine("Connected To: " & ex.Errors.Item(i).Source)
        Console.WriteLine("Server: " & ex.Server)
    Next i
End Try

Result:
Class:
Error #: 17
Error Message: SQL Server does not exist or access denied.
Line Number: 0
Connected To: .Net SqlClient Data Provider
Server: BADSERVER

This article has provided you with a way to use the OleDbException and SqlException classes to debug database communication issues. These classes can also be used in exception handlers that catch the exception, determine the problem, and take remedial action at runtime e.g. reverse a failed update attempt.

Learn more about the OleDbException and SqlException classes by visiting the links below.

SQL Exception

OLEDB Exception

by John Spano

.NET has an interesting and very useful concept called Reflection. Since your compiled programs in .NET are compiled to IL and not machine code, it is very easy to query an EXE or DLL for what information it exposes in the form of classes, methods and properties, etc. In this article I will show you how to create a very simple and easy method for "plug-in" type architectures.

Our project will consist of 2 DLL's and one EXE. Our EXE will show a list box and fill it with any strings of information it finds in compatible classes. When you double click on the box, it will dynamically call the corresponding class that placed the string in the box. Our regular class will have one string and our plug-in class will have another, if the EXE finds the DLL in its directory.

As with all good architectures, we will start with an interface. The interface defined below will be the contract between our main EXE and any plug-in DLL's that exist. We put the interface in its own DLL so other people can use it. It is typical to have a DLL that is specifically for your interfaces. This allows any other projects to get to them easily. You can also have more control over the distribution of it when others want to add plug-ins to your application. Ours is simple for this demo, but it can be as complex as you need it. Here is its definition:

Public Interface IShowInListBox 
    Property TextValue() As String 
    Sub SayHello() 
End Interface 

It has a single property and a sub. The property will return the line of text that we want to show in the list box. The sub will be the code that gets fired when we double click on the item in the list box. Any class that wants to be recognized by our main EXE as a plug-in will have to implement this interface.

We will now look at our two classes that will implement this interface. One is in our main EXE. This one will function as "standard functionality" of our app. The other class is in our second DLL. This one will function as our plug-in class. Here are the definitions.

First the standard one:

Imports System.Windows.Forms 
Public Class MyListItem 
    Implements ReflectionInterfaces.IShowInListBox 

    Sub SayHello() Implements ReflectionInterfaces.IShowInListBox.SayHello 
        MessageBox.Show("Hello from My Exe!") 
    End Sub 

    Property IShowInListBox_TextValue() As String _ 
            Implements ReflectionInterfaces.IShowInListBox.TextValue 
        Get 
            Return "ListBox Item From Exe" 
        End Get 
        Set(ByVal Value As String) 
        End Set 
    End Property 
End Class 

Now the plug-in class:

Imports System.Windows.Forms 
Public Class DllListItem 
    Implements ReflectionInterfaces.IShowInListBox 

    Sub SayHello() Implements ReflectionInterfaces.IShowInListBox.SayHello 
        MessageBox.Show("Hello from a DLL Class!") 
    End Sub 

    Property IShowInListBox_TextValue() As String _ 
            Implements ReflectionInterfaces.IShowInListBox.TextValue 
        Get 
            Return "ListBox Item From a DLL Class" 
        End Get 
        Set(ByVal Value As String) 
        End Set 
    End Property 
End Class 

You will notice that they are almost exactly the same. The only difference being their name, what they show in the message box, and the strings they return to show in the list box. Notice also that both of the classes implement ReflectionInterfaces.IshowInListBox. ReflectionInterfaces is the name of the namespace I put our interface in.

We'll complete our look at this next week in the second part: Putting the two DLLs to work in a Win Forms application.

Advertisement

Anand Narayanaswamy has been testing the Enterprise edition of WebGrid .NET Enterprise from Intersoft Solutions and found much that he liked, as well as some minor areas for improvement.

He notes that the product ships with numerous features with which you can easily build enterprise-level and highly professional data presentation applications in less time and codes. It is designed to deliver enterprise-class information through hierarchical navigations with sophisticated user interaction. This allows users to work with the information in a more effective and productive way.

Read the full review at:
http://www.devcity.net/net/article.aspx?alias=webgridnet

http://www.devcity.net/net/article.aspx?alias=webgridnet
Advertisement

We encourage you to pass this issue of
.net.devcity.weekly on to anyone you know with an interest in .NET technology and News You Can Compile

Manage Your Subscription Here.

You are currently subscribed as '*EMAIL*' to .net.devcity.weekly.

Click here to unsubscribe.

Thanks for reading!

DevCity.NET is hosted by FullControl.NET

Copyright vbCity.com, LLC 2003. All Rights Reserved.