![]() |
General Programming »
Programming Tips »
General
Beginner
License: The Code Project Open License (CPOL)
Tips for Beginner when creating First Desktop applicationBy Rupesh Kumar SwamiAn 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
|
||||||||||
|
Advanced Search |
|
|
|
||||||||||||||||
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.
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.
This article contains following three issue
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"
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.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 SubAbove 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 FunctionIn 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 FunctionIn 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 SubAbove 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 SubPurpose 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.
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 Functionwhen 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.
There are also some issue when we design the interface of Desktop application. I point out some of them one by one
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
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 |