Click here to Skip to main content
6,306,412 members and growing! (17,216 online)
Email Password   helpLost your password?
General Programming » Programming Tips » General     Beginner License: The Code Project Open License (CPOL)

Tips for Beginner when creating First Desktop application

By Rupesh Kumar Swami

An article for beginner, that describe that how can we apply form level validation and some common database function
VB (VB 8.0, VB 9.0)WinXP, Vista
Version:2 (See All)
Posted:4 Jan 2009
Views:4,470
Bookmarked:15 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
10 votes for this article.
Popularity: 2.16 Rating: 2.16 out of 5
5 votes, 50.0%
1
1 vote, 10.0%
2

3
2 votes, 20.0%
4
2 votes, 20.0%
5

Introduction

First of all, this article is totally for Beginner. So there is not any special thing for Intermediate and Advanced level programmer.

This article demostrate that how can we design forms in .NET application, apply appropriate validation(field level and form level) on  controls and use some function to perform database operation.

These are some tips for commonly faced problems by beginner in .NET . Some of these tips are mine and some of these i have got from different sources. My aim is not to claim the ownership of these tips,but as a newcomer I had faced these problems and had to do lot of googling. So just to help my fellow programmers I am putting this together. 

Background

I have 2.5 year Experience in .NET. My primary role is guide(or handle) to my sub-ordinate and new programmers during development of desktop application.During this, i feel that many new commers make common mistake like write seprate code for validation for each control, create databse connection object(Connection, DataSet, DataAdapter etc) on each form or even in each procedure, place Controls anyware in form etc. So i think why not i share this knowledge with other new commers which is not in my company. 

Content

This article contains following three issue

  1. Form Level Validation Function
  2. Database Related Function
  3. User Interface Related Tips

Form Level Validation Function

For all type of validation, i create a module(mdcheking) which hold some public variable and function.First of all we declare some public variable as following

 Public msgboxTitle As String = "My Application Title"
 Public MessageBoxMessage As String = "Can not leave mandatory field as blank"

 
Variable msgboxTitle hold the title of the application and  it is displayed in title bar of Message Box. Variable MessageBoxMessage hold the message which we want to prompt to user.It contains fixed string which prompt to user to fill or select compulsory fields.

Now we discuss other function(or procedure) one by one. However this function is very simple but it is very useful for beginners.
 
 Public Sub Prompt(ByVal MessageBoxMessage As String, Optional ByVal MessageBoxTitle As String = Nothing)
 	If MessageBoxTitle = Nothing Then 
		MsgBox(MessageBoxMessage, MsgBoxStyle.Information, msgboxTitle)
 	Else
	 	MsgBox(MessageBoxMessage, MsgBoxStyle.Information, MessageBoxTitle)
 	End If
 End Sub        
        
Above function take two argument. First argument MessageBoxMessage contains the message which we want to display the user.  Second argument MessageBoxTitle is optional. In some cases , we want to display some other title in message box in place of Application title. So in this case we supply some value for second argument otherwise there is no requirement to pass second argument when we call this method.

 
 Public Function IsBlankTextBox(ByRef st As TextBox, Optional ByVal PromptMessage As String = Nothing,_
						Optional ByVal MessageBoxTitle As String = Nothing) As Boolean
        If st.Text.Trim = "" Then
            If PromptMessage = Nothing Then
                If MessageBoxTitle = Nothing Then
                    Prompt(MessageBoxMessage)
                Else
                    Prompt(MessageBoxMessage, MessageBoxTitle)
                End If
            Else
                If MessageBoxTitle = Nothing Then
                    Prompt(PromptMessage)
                Else
                    Prompt(PromptMessage, MessageBoxTitle)
                End If
            End If
            st.Focus()
            Return True
        Else
            Return False
        End If

 End Function
        
In above function, we check whether Text property of supplied TextBox  is blank or not? If it is blank then it prompt the user and set focus to appropriate field and return True otherwise it returns False. It takes three argument. In First parameter st, we supply a TextBox as Byref. Second and third parameter is optional. If last two parameter is supplied then supplied message and title is appear in message box otherwise it show our application title and message which we already declared in declaration section of module.

 
 Public Function IsBlankComboBox(ByVal st As ComboBox, Optional ByVal PromptMessage As String = Nothing,_
						Optional ByVal MessageBoxTitle As String = Nothing) As Boolean 
	 If st.Text.Trim = "" Then 
		If PromptMessage = Nothing Then 
			If MessageBoxTitle = Nothing Then 
				Prompt(MessageBoxMessage)
			Else 
				Prompt(MessageBoxMessage, MessageBoxTitle)
			End If
		Else
			If MessageBoxTitle = Nothing Then
				Prompt(PromptMessage)
			Else 
			 	Prompt(PromptMessage, MessageBoxTitle) 
			End If
	 	End If
	 	st.Focus()
	 	Return True
	 Else
	 	Return False
	 End If
 End Function        
In above function, we check whether Text property of supplied ComboBox is blank or not? If it is blank then it prompt the user and set focus to appropriate field and return True otherwise it returns False. It takes three argument. In First parameter st, we supply a ComboBox as Byref. Second and third parameter is optional. If last two parameter is supplied then supplied message and title is appear in message box otherwise it show our application title and message which we already declared in declaration section of module.

 
 Public Sub CheckPressedKeyForAlphabates(ByVal key As System.Windows.Forms.KeyPressEventArgs)
        If Not (Char.IsControl(key.KeyChar) Or Char.IsLetter(key.KeyChar) Or Char.IsWhiteSpace(key.KeyChar) _
	Or key.KeyChar = "." Or key.KeyChar = "&") Then
            key.Handled = True
        End If
 End Sub
        
In above function, we simply pass a key which is checked whether it is related to any alphabates (or within any control keys or white space or decimal sign or "&" sign) then it is allowed otherwise it is rejected. This procedure does not allow any other character which is not in above specified range. This procedure is generally use on Keypress event of TextBox

 
 Public Sub CheckPressedKeyForNumericWithoutDot(ByVal key As System.Windows.Forms.KeyPressEventArgs)
        If Not (Char.IsControl(key.KeyChar) Or Char.IsNumber(key.KeyChar)) Then
            key.Handled = True
        End If
 End Sub
        
In above function, we simply pass a key which is checked whether it is related to any number (or within any control keys ) then it is allowed otherwise it is rejected. This procedure does not allow any other character which is not in above specified range. This procedure is generally use on Keypress event of TextBox .
        
 Public Sub CheckPressedKeyForNumericWithDot(ByVal key As System.Windows.Forms.KeyPressEventArgs, ByVal str As String)
        If str.Contains(".") Then
            CheckPressedKeyForNumericWithoutDot(key)
        Else
            If Not (Char.IsControl(key.KeyChar) Or Char.IsNumber(key.KeyChar) Or key.KeyChar = ".") Then
                key.Handled = True
            End If
        End If
 End Sub
        
Above function is same as CheckPressedKeyForNumericWithoutDot  except with one difference.It allow only single decimal symbol. Second Parameter is contains the original string which first check whether it contains any decimal symbol or not? If it contains any decimal symbol, then Key is passed to CheckPressedKeyForNumericWithoutDot which allow only numeric value and if second parameter does not contains any decimal symbol, then it allowed numeric value with decimal symbol.

        
 Public Sub CheckPhoneNo(ByVal key As System.Windows.Forms.KeyPressEventArgs)
	If Not (Char.IsControl(key.KeyChar) Or Char.IsNumber(key.KeyChar) Or key.KeyChar = "-" _
	Or key.KeyChar = ",") Then
     		key.Handled = True
	End If
 End Sub
        
Purpose of above function is allow only Telephonic character. It allow any digit,comma(,) and hypen(-) . If supplied key is within these character, then it is allowed otherwise it is rejected.

        
 Public Function imageToByteArray(ByVal ImageIn As System.Drawing.Image) As Byte()
        Dim ms As MemoryStream = New MemoryStream()
        Dim FormatImage1 As Imaging.ImageFormat = ImageIn.RawFormat
        ImageIn.Save(ms, FormatImage1)
        Return ms.ToArray()
 End Function
        
At beginner level, everyone is struggling when he/she want to save image into database (i am also face this problem).So i want to say that first convert the image into byte array and strore this byte array in database. Above function convert the image into byte array. 
         
 Public Function ByteArrayToimage(ByVal ImageArray As Byte()) As Image
        Dim ms As MemoryStream = New MemoryStream(ImageArray)
        Dim ReturnImage As Image = Image.FromStream(ms)
        Return ReturnImage
 End Function
        
When we retrive image data from database, then it is in raw format (byte).Simply convert this byte array into image and use it.Above function convert the byte array into image. 

Database Related Function

There are also some commonly mistake made by beginner.They create database related object (like connection, Data Adapter, connection string etc.) on each form (or some time in each procedure).So here i want to show that there are no requirement to use database related object (and namespace) on each form.we can create this object (and some function for access database) in  class (or module.I prefer class). For this article , i use MSAccess database. Since on initial stage, everyone prefer this simple database.

In declaration section of class, we create some database related variable which is used mostly like connection object, connection string etc. 

       
 Private ConnString As String = "Provider=Microsoft.jet.oledb.4.0;data source=" & mdChecking.DatabasePath
 Private con As OleDbConnection
 Private com As OleDbCommand
 Private da As OleDbDataAdapter
       
ConnString contains the database provider  and data source info. I think there are no requiremnet to describle all other variable. Since you can easily guess its role from their data type. 
        
 Public Function ReturnSingleValue(ByVal MyQuery As String) As Object
        Try
            con = New OleDbConnection(ConnString)
            com = New OleDbCommand(MyQuery, con)
            con.Open()
            Dim result As Object = com.ExecuteScalar
            con.Close()
            If IsDBNull(result) Then
                Return Nothing
            End If

            Return result
        Catch ex As Exception
            mdChecking.Prompt(ex.Message.ToString)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
        Return Nothing
 End Function
        
when we want to only single value from database table, then we use above function .
         
 Public Function InsertDeleteUpdate(ByVal MyQuery As String) As Long
        Try
            con = New OleDbConnection(ConnString)
            com = New OleDbCommand(MyQuery, con)
            con.Open()
            Dim RowsAffected As Long
            RowsAffected = com.ExecuteNonQuery()
            con.Close()
            Return RowsAffected
        Catch ex As Exception
            mdChecking.Prompt(ex.Message.ToString)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
        Return Nothing
 End Function
        
when we want to simply insert record or delete record or update record, then we use above function.
         
 Public Function ReturnMultipleValue(ByVal MyQuery As String) As DataSet
        Dim ds As DataSet
	Try
            con = New OleDbConnection(ConnString)
            da = New OleDbDataAdapter(MyQuery, con)
            ds = New DataSet
            con.Open()
            da.Fill(ds)
            con.Close()
            Return ds
        Catch ex As Exception
            mdChecking.Prompt(ex.Message.ToString)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
	Return ds
 End Function
        
whenever we want to get multiple records , then we use above function. In above function i fill the records in Dataset table, however you can directly fill the record in DataTable.
         
 Public Sub ExecuteCommandQuery(ByVal comm As SqlCommand)
        Try
            con = New SqlConnection(ConnString)
            comm.Connection = con
            con.Open()
            comm.ExecuteNonQuery()
            con.Close()
        Catch ex As Exception
            mdChecking.Prompt(ex.Message.ToString)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
 End Sub
        
Above function is also used when we want to insert or delete or update the record. This function is specially created to insert images in database. 

User Interface Related Tips

There are also some issue when we design the interface of Desktop application. I point out some of them one by one

  1. Font name and size should be standard for complete application.
  2. If you use menu strip, then a window menu must reside there.
  3. Use seperator in menu for group related fields.
  4. Make sensible caption text for error messages, labels and form titles.
  5. Use meaningful name for each control and form (not like button1,Textbox1, form1 etc.)
  6. Use prefix for controls and forms (like lbl for Label, txt for TextBox, cmb for ComboBox, frm for Form etc.)
  7. Use progressbar when any task takes too much time.
  8. Absolutely no spelling errorrs.
  9. Place red asterisk (or error provider) for mandatory fields.
  10. Sometime two words carry different meaning with a slight change in spelling.  Make sure you use the correct one (for example, Principle  and  Principal, Labor and Labour etc.)
  11. If you are working for International customer, then date should be in right format.
  12. Colors should be easy to eye and pleasing.No fancy colors unless you need to highlight something.
  13. Hot Keys should be defined for every possible option.
  14. Check anchoring for each and every control on form.
  15. Set dock for controls, whenever required.
  16. Tab order should be proper(in sequence).
  17. Order of fields should be very relevant. (for example in Employee form, you should  keep personal detail related fields in one group and official detail related field in another group).
  18. If you are using group box to categorize the fields, then they should be even space from left and right edge of form.
  19. If maximize is not required, then make form border as fixed single and disable maximize button.
  20. Individual forms should carry the same icon as there for menu item.
  21. Button height and width should be standard for complete application.
  22. If possible, Button location should be standard for complete application (for example, Close button location should be standard for each and every form)
  23. Label and their corresponding control (TextBox, ComboBox etc.) should be aligned with Vertical Center.
  24. Gap between labels and their corresponding control should be even for complete application.
  25. If possible, then set maximum length for TextBox.
  26. Field like ComboBox, CheckListBox must be sorted.
  27. If icons are being used, they look sensible and relative, not attractive.
  28. If You use Datagridview, then Column headers must be middle aligned.
  29. If you bind the Datagridview, then column headers must have some relevant name(not the database field name).
  30. In Datagridview, numeric field should be right aligned and all of the rest field should be left aligned.
  31. If application is MDI, then any change in single form should reflect to all other related form if these form is open ( for exaple there are multiple form is open which is related to employee and you used Employee name and their father's name related field in each form and now if we change the Employee name or father name in main employee form, then this should be reflect in all other opened form.)

History

Posted: 4 Jan 2009.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rupesh Kumar Swami


Member
Currently I'm working as a Software Developer in Integrated Solution(ISOL),Bikaner(RAJ.), INDIA. I possess following degrees:


* MCA from Rajasthan University, Jaipur(RAJ.), INDIA.
* PGDCA from Rajasthan University,Jaipur(RAJ.), INDIA.
* BSc (Maths) from Mahareshi Dayanand Saraswati University, AJmer(RAJ.), INDIA.


Award: Best VB.NET article of June 2008: Create Column Charts Using OWC11
Occupation: Software Developer
Company: Integrated Solution
Location: India India

Other popular Programming Tips articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmvpDave Kreskowiak9:41 8 Jan '09  
GeneralMy vote of 1 Pinmembermaspr2:35 8 Jan '09  
GeneralMy vote of 1 Pinmembersuresh suthar18:33 5 Jan '09  
GeneralMy vote of 1 PinmemberJammer7:03 5 Jan '09  
Generala few pointers.. PinmemberSeishin#1:52 4 Jan '09  
GeneralRe: a few pointers.. PinmemberRupesh Kumar Swami21:27 4 Jan '09  
GeneralRe: a few pointers.. PinmemberSeishin#23:07 4 Jan '09  
GeneralMy vote of 2 PinmemberBram Fokke1:17 4 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 Jan 2009
Editor: Sean Ewington
Copyright 2009 by Rupesh Kumar Swami
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project