Here is simple Notification Bar control (like we see in Internet Explorer). Gives application a good look. Note that I haven't done much thing, you can customize is further if you like. It supports blinking too.
Usage:
ShowNotification() method to display the Notification.
BlinkTimes property to set the Number of Times to blink.
Download Source Code:
Notificationbar.zip
Showing posts with label VS 2005. Show all posts
Showing posts with label VS 2005. Show all posts
Saturday, February 14, 2009
Notification Bar Control For Windows Forms (Win Forms)
Here is simple Notification Bar control (like we see in Internet Explorer). Gives application a good look. Note that I haven't done much thing, you can customize is further if you like. It supports blinking too.
Usage:
ShowNotification() method to display the Notification.
BlinkTimes property to set the Number of Times to blink.
Download Source Code:
Notificationbar.zip
Monday, January 26, 2009
DataGridView Custom Cell ToolTip
Level: Intermediate
Knowledge Required:- DataGridView Control
- Windows Forms
Friday, January 23, 2009
NOT Focusable / NOT Selectable Button
Level: Intermediate
Knowledge Required:
User Controls
Description:
Few days back I was creating a user control like ComboBox. In ComboBox we have a Drop Down button at the right side, which cannot have focus. This button can only be clicked by mouse to open the Drop Down portion (Alt+Down is the shortcut).
Similarly my control also have a button on right. I decided to make that button just like the Drop Down button of ComboBox. For this purpose I added a plain Class in my project and then put the following Code,
Knowledge Required:
User Controls
Description:
Few days back I was creating a user control like ComboBox. In ComboBox we have a Drop Down button at the right side, which cannot have focus. This button can only be clicked by mouse to open the Drop Down portion (Alt+Down is the shortcut).
Similarly my control also have a button on right. I decided to make that button just like the Drop Down button of ComboBox. For this purpose I added a plain Class in my project and then put the following Code,
Public Class NotSelectableButton
Inherits Button
Public Sub New()
MyBase.New()
' following line will make this button Not Focusable
SetStyle(ControlStyles.Selectable, False)
End Sub
End Class
Saturday, January 17, 2009
FTP File Upload Error
It seems that our Network Administrator has changed some settings because my previous file uploading code is NOT working. And giving the following exception:
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.
I was using the VB.net My namespace,
Then I modified and created my own upload function as,
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.
I was using the VB.net My namespace,
My.Computer.Network.UploadFile("C:\SomeFile.txt", "ftp://ftpsite/somefile.txt", "userid", "pwd")So I Googled about that error and found some dicussion on MSDN forums.Then I modified and created my own upload function as,
Private Sub UploadFile(ByVal sDestination As String, ByVal sSource As String, ByVal sUserID As String, ByVal sPassword As String)
Dim i As System.Net.FtpWebRequest
Dim us As System.IO.Stream
Dim filebytes As Byte()
' create the FTP Web Request
i = System.Net.WebRequest.Create(sDestination)
' set credentials
i.Credentials = New System.Net.NetworkCredential(sUserID, sPassword)
' method = Upload File
i.Method = System.Net.WebRequestMethods.Ftp.UploadFile
i.UsePassive = False
i.Proxy = Nothing
' get the Request Stream
us = i.GetRequestStream()
' get the file bytes from source
filebytes = My.Computer.FileSystem.ReadAllBytes(sSource)
' write the bytes in stream
us.Write(filebytes, 0, filebytes.Length)
' close the stream
us.Close()
End Sub
Warning! Above function will read all the bytes (in one go) from file. Which is NOT a good practice for larger files.
Tuesday, December 23, 2008
Image to Byte Array and Byte Array to Image
Level: Intermediate
Knowledge Required:
Image Class
Description:
Here are simple functions that convert an Image into Byte Array and Byte Array into Image. An image is required to be converted into bytes array when we save it in Database, hence on reading the bytes from database, it needs to be converted back into image.
Knowledge Required:
Image Class
Description:
Here are simple functions that convert an Image into Byte Array and Byte Array into Image. An image is required to be converted into bytes array when we save it in Database, hence on reading the bytes from database, it needs to be converted back into image.
Private Function BytesToImage(ByVal ImageBytes() As Byte) As Image
Dim imgNew As Image
Dim memImage As New System.IO.MemoryStream(ImageBytes)
imgNew = Image.FromStream(memImage)
Return imgNew
End Function
Private Function ImageToBytes(ByVal Image As Image) As Byte()
Dim memImage As New System.IO.MemoryStream
Dim bytImage() As Byte
Image.Save(memImage, Image.RawFormat)
bytImage = memImage.GetBuffer()
Return bytImage
End Function
Tuesday, November 18, 2008
Setting Window / Form Position Programmatically
Level: Beginner
Knowledge Required:
Windows Forms
Description:
While working with Windows Forms we sometimes require to set the Window/Form Position manually before we show it. Consider the following code:
If we execute the above code, it is NOT sure that window will be displayed at 10, 10. Because we haven't set the StartPosition property. By default this property is equal to WindowsDefaultLocation that is why whenever we display the Form, Windows Operating system choose where to put it. And if we change Location after the frmNew.Show(), then our location will set.
To set the Location programmatically we should first set the StartPosition property as,
Knowledge Required:
Windows Forms
Description:
While working with Windows Forms we sometimes require to set the Window/Form Position manually before we show it. Consider the following code:
Dim frmNew as Form2
frmNew = New Form2()
frmNew.Location = New Point(10, 10)
frmNew.Show()
If we execute the above code, it is NOT sure that window will be displayed at 10, 10. Because we haven't set the StartPosition property. By default this property is equal to WindowsDefaultLocation that is why whenever we display the Form, Windows Operating system choose where to put it. And if we change Location after the frmNew.Show(), then our location will set.
To set the Location programmatically we should first set the StartPosition property as,
Dim frmNew as Form2
frmNew = New Form2()
frmNew.StartPosition = FormStartPosition.Manual
frmNew.Location = New Point(10, 10)
frmNew.Show()
Sunday, September 14, 2008
Binding DataGridView ComboBox Column
Level: Beginner
Knowledge Required:- Data Binding
- DataGridView
OrderDataSet
First we will create a simple User Interface,
As you can see in the above figure, the DataGridView control is bind with OrderDetail Table. Note that the Product_ID column is displaying ID which is NOT a friendly approach. Instead Product Name should be displayed here. We can use the DataGridView's ComboBox Column here, in which we will populate all the products.
The main point to be focused here is that, we will be binding the DataGridView control with the same OrderDetail DataTable, in which there is no Product_Name column. But on front-end the Product_ID column will be set to ComboBox Column in which we will populate the Products' Name.
Since we need to populate the ComboBox with Products' Name. Therefore we will add another Typed DataSet and BindingSource to our Form,
We have bind our ProductBindingSource with ProductDataSet which contains Product DataTable. We will fill this table in Form_Load event Handler.
IMPORTANT: This table needs to be filled before we fill the OrderDataSet OR at-least before the OrderDetail DataGridView is displayed
Now we need to setup the Product_ID column. First set the ColumnType of Product_ID column to DataGridViewComboBoxColumn and then set the properties as,- DataPropertyName = Product_ID
- DataSource = ProductBindingSource
- DisplayMember = Product_Name
- ValueMember = Product_ID
DataPropertyName: tells that Product_ID column of OrderDetail DataTable should be updated
DataSource: is the source from where the list of Products will be taken, in this case the ProductBindingSource which is actually bind with Product DataTable
DisplayMember: Column of Product DataTable which should be used to display in DataGridView control
ValueMember: Column of Product DataTable which should be used to set the Value in DataGridView which ultemately will send the value in OrderDetail DataTable
Download:
BindingDataGridViewComboBox.zip
Thursday, September 11, 2008
How to handle Overlapping of Large Text Fields in Crystal Reports
Level: Intermediate
Knowledge Required:
Crystal Reports
Description:
While working in Crystal Reports, we sometimes face a scenario when we need to put a Large Text Field (which can grow upto multiple lines). The issue comes if we try to put another Field after this Text Field. Example:

As you can see in above I have put to Formula Fields, both will contain Large Text which may expand. So here is the preview,

Therefore to solve this issue we can create multiple sub-sections in the same section. This can be achieved by Section Expert.

Now we will put the Fields in different sub-sections as,

And here is the preview again,

Note that in Crystal Reports Sections automatically expand, that is why when the first Text Field expands, the section also expands itself, therefore ultimately the next field renders properly.
Knowledge Required:
Crystal Reports
Description:
While working in Crystal Reports, we sometimes face a scenario when we need to put a Large Text Field (which can grow upto multiple lines). The issue comes if we try to put another Field after this Text Field. Example:

As you can see in above I have put to Formula Fields, both will contain Large Text which may expand. So here is the preview,

Therefore to solve this issue we can create multiple sub-sections in the same section. This can be achieved by Section Expert.

Now we will put the Fields in different sub-sections as,

And here is the preview again,

Note that in Crystal Reports Sections automatically expand, that is why when the first Text Field expands, the section also expands itself, therefore ultimately the next field renders properly.
Thursday, September 4, 2008
Using DataGridView CheckBox Column as RadioButton (OptionButton)
Level: Beginner
Knowledge Required:- DataGridView Control
- Data Binding
- Created a back-end logic when user clicks on CheckBox Column so only one CheckBox should be checked at a time
- Change the look of CheckBox column so it looks a Radio Button Column
As you can see there are 2 columns. The IsSelected column is actually a Boolean column which is normally rendered as CheckBox in DataGridView control. What we will be doing is that we first set our DataGridView to Read Only i.e.,
AllowUserToAddRows = False
AllowUserToDeleteRows = False
ReadOnly = True
We are making our DataGridView control Read Only because it is easier to set the CheckBox checked or unchecked programmatically otherwise DataGridView control itself will be interfering and will create problems and complexities for us.
OK now whenever user clicks on CheckBox we will be performing our custom operation. To do this we will use the DataGridView’s CellContentClick event. Here is the code,
Private Sub ShutDownOptionsDataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles ShutDownOptionsDataGridView.CellContentClick
If e.ColumnIndex = Me.columnIsSelected.Index Then
Dim drv As DataRowView
Dim rowShutDownOption As ShutdownOptionDataSet.ShutDownOptionsRow
' in this event handler we know that which DataGridView's row is clicked
' so we are going to extract out the actual DataTable's row which is
' bind with this DataGridView's Row
drv = CType(Me.ShutDownOptionsDataGridView.Rows(e.RowIndex).DataBoundItem, DataRowView)
' get the DataTable's row
rowShutDownOption = CType(drv.Row, ShutdownOptionDataSet.ShutDownOptionsRow)
' get the row which is currently selected
Dim rowCurrentlySelected() As ShutdownOptionDataSet.ShutDownOptionsRow
rowCurrentlySelected = Me.ShutdownOptionDataSet.ShutDownOptions.Select("IsSelected=True")
' if some row found then make it de-selected
If rowCurrentlySelected.Length > 0 Then
rowCurrentlySelected(0).IsSelected = False
End If
' ok now select the row which is clicked
rowShutDownOption.IsSelected = True
End If
End Sub
What we do is first get the row in which IsSelected=True and we make that row IsSelected=False. Then we set the row which is clicked as IsSelected=True.
Next thing is to change the look of CheckBox to OptionButton / RadioButton. For this purpose we will be using DataGridView’s CellPainting event. Here is the code,
Private Sub ShutDownOptionsDataGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles ShutDownOptionsDataGridView.CellPainting If e.ColumnIndex = Me.columnIsSelected.Index AndAlso _ e.RowIndex >= 0 Then e.PaintBackground(e.ClipBounds, True) Dim rectRadioButton As Rectangle rectRadioButton.Width = 14 rectRadioButton.Height = 14 rectRadioButton.X = e.CellBounds.X + (e.CellBounds.Width - rectRadioButton.Width) / 2 rectRadioButton.Y = e.CellBounds.Y + (e.CellBounds.Height - rectRadioButton.Height) / 2 If IsDBNull(e.Value) OrElse e.Value = False Then ControlPaint.DrawRadioButton(e.Graphics, rectRadioButton, ButtonState.Normal) Else ControlPaint.DrawRadioButton(e.Graphics, rectRadioButton, ButtonState.Checked) End If e.Paint(e.ClipBounds, DataGridViewPaintParts.Focus) e.Handled = True End If End SubAs you can see we have used the ControlPaint class to draw the RadioButton / OptionButton. Download: DGVCheckBoxAsRadioButton.zip
Wednesday, September 3, 2008
Asynchronous Data Loading using TableAdapter with Cancel Feature
Level: Intermediate
Knowledge Required:
- BackgroundWorker Control
- DataGridView Control
- Data Binding
- TableAdapter
CREATE PROCEDURE [dbo].[GetStudent]
AS
BEGIN
SET NOCOUNT ON;
-- here we are simulating a very long query
-- which takes 3 seconds to complete
WAITFOR DELAY '00:00:03';
SELECT *
FROM tbl_Student;
END
In this procedure I have added a WAITFOR DELAY SQL Statement. Which simulates a long query that takes time 3 seconds. We will call this procedure from our TableAdapter to fill the DataTable.
Now we will add the SQLCommand Cancel stuff in our TableAdapter. This can be achieved by creating a Partial Class of TableAdapter,
Namespace TestDataSetTableAdapters
Partial Class StudentTableAdapter
Public Sub CancelSelect()
Me.Adapter.SelectCommand.Cancel()
End Sub
End Class
End Namespace
As you see I have given the name of method CancelSelect which actually cancels the SelectCommand of Adapter. Note that I haven’t implemented any checking here (for example is command executing or NOT). This is upto the user of TableAdapter class. He/She will be responsible to check before executing this method.
Here we have done with our TableAdapter. Now next thing is to implement the loading in the different Thread. For this purpose I have used the BackgroundWorker control which is quite simple. The overall idea is,
- Create 2 buttons
- LoadButton
- CancelButton
- When LoadButton is clicked
- Execute the BackgroundWorker
- In BackgroundWorker DoWork Event Handler
- Note somewhere that Execution is started
- Execute the Fill() Method of TableAdapter
- When CancelButton is clicked
- Check if execution is started then
- Execute the CancelSelect() method of TableAdapter
Public Class Form1
' ErrorText will contain the error information if occurred
' while loading data in different thread
Private _ErrorText As String
' this boolean variable will be true when command is executed
Private _CommandExecuted As Boolean
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
' first we will disable the Load button so it should NOT be clicked again
Me.btnLoad.Enabled = False
' then we will enable the Cancel button so the command can be canceled
Me.btnCancel.Enabled = True
' set the status text
Call Me.SetStatusText("Loading...")
' clear the Error Text
Me._ErrorText = ""
' here we have first clear the currently loaded data
' from DataSet, because the Adapter will fill the DataSet
' in different thread, therefore it will create problems
' while displaying the same data (which is being modified
' in different thread) in DataGridView
Me.TestDataSet.Clear()
' start the asynchronous task
Me.BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
' first set the executed flag
Me._CommandExecuted = True
' execute the command
Me.StudentTableAdapter.Fill(Me.TestDataSet.Student)
Catch ex As Exception
_ErrorText = ex.Message
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
' ok our data is loaded now
' so enable the Load button
Me.btnLoad.Enabled = True
' disable the Cancel button
Me.btnCancel.Enabled = False
' if NO error was occurred in thread
If Me._ErrorText = "" Then
Me.SetStatusText(Me.TestDataSet.Student.Count & " Records loaded")
Else ' else (some error was occurred)
Me.SetStatusText(Me._ErrorText)
End If
' since data is changed in different thread
' therefore by reseting the Bindings the DataGridView
' will refresh itself and will display all the data
Me.StudentBindingSource.ResetBindings(False)
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
' if command is executed then
If Me._CommandExecuted Then
' cancel it
Me.StudentTableAdapter.CancelSelect()
End If
End Sub
Private Sub SetStatusText(ByVal sText As String)
Me.lblStatus.Text = sText
End Sub
End Class
Download:
TableAdapterWithCancel.zip
Note: The zip file contains TestDBScript.sql T-SQL Script which will,
1) Create a database "TestDB"
2) Create a table "tbl_Student" in that database
3) Create a Stored Procedure "GetStudent"
4) Put some data in tbl_Student
Please execute this script before running the project.
Tuesday, August 12, 2008
Query Timeout in ADO.Net but NOT in SQL Server Management Studio
I was facing this issue for a while that I have created a Stored Procedure in SQL Server 2005 Database that performs a search on a table (according to the given parameters). It was happening that when this procedure was executed from ADO.net (my front-end Visual Basic Application) Timeout exception was occurring. But at the same time when we execute this procedure from SQL Server Management Studio it executes immediately.
The Timeout in Visual Basic Application was NOT coming immediately it was coming after some time when users execute the procedure many times. Whenever time out occurred, I went in the SQL Server Management Studio and just did ALTER (without changing a single thing in procedure). And the problem resolved for some time NOT permanently.
So I put this question on MSDN Forums and a member told me to put the WITH RECOMPILE in the procedure. He told me that
"I think the problem is with the cache. When you ALTER the procedure from Management Studio it is recompiled and the problem is fixed. this is my guess."
It sure fixed my problem and the Timeout never came afterwords. Here is the link to that post.
http://social.msdn.microsoft.com/Forums/en-US/...
The Timeout in Visual Basic Application was NOT coming immediately it was coming after some time when users execute the procedure many times. Whenever time out occurred, I went in the SQL Server Management Studio and just did ALTER (without changing a single thing in procedure). And the problem resolved for some time NOT permanently.
So I put this question on MSDN Forums and a member told me to put the WITH RECOMPILE in the procedure. He told me that
"I think the problem is with the cache. When you ALTER the procedure from Management Studio it is recompiled and the problem is fixed. this is my guess."
It sure fixed my problem and the Timeout never came afterwords. Here is the link to that post.
http://social.msdn.microsoft.com/Forums/en-US/...
Wednesday, July 30, 2008
Another look at Exception Handling
Level: Beginner
Knowledge Required:
As we have used the Exception Handling (Try...Catch) many times. But in this post we shall understand an important aspect. Consider the following code,
As you can see this method will be inserting data in 2 tables. Our goal is,
Begin the Transaction
Try to Insert the Data in Tables
If no error occurs on Insertion then Commit the Transaction
If error occurred then
Rollback the Transaction
Again throw the Exception (so the caller is being notified)
End If
At the end (whether exception is occred or NOT) Close the connection
Knowledge Required:
- Exception Handling
- ADO.net
As we have used the Exception Handling (Try...Catch) many times. But in this post we shall understand an important aspect. Consider the following code,
Private Sub InsertSomeData()
Dim conn As SqlClient.SqlConnection = Nothing
Dim cmd As SqlClient.SqlCommand
Dim tran As SqlClient.SqlTransaction = Nothing
Try
' initialize connection
conn = New SqlClient.SqlConnection("Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True")
' open connection
conn.Open()
' begin transaction
tran = conn.BeginTransaction
' create a Command
cmd = conn.CreateCommand()
' setup command to insert data in 1st table
cmd.CommandText = "INSERT INTO MyTable1(Column1) VALUES('Data in MyTable1.Column1')"
cmd.ExecuteNonQuery()
' setup command to insert data in 2nd table
cmd.CommandText = "INSERT INTO MyTable2(Column1) VALUES('Data in MyTable2.Column1')"
cmd.ExecuteNonQuery()
' ok now commit the changes
tran.Commit()
Catch ex As Exception
' an exception is occurred
' check if transaction has been initialized then
 ' rollback
If tran IsNot Nothing Then
tran.Rollback()
End If
' again throw the exception
' this is because we want the caller to be notified
Throw ex
Finally
' finally block will be executed anyway
' whether the exception is occurred or NOT
' ================---------------------
' Note: we are again throwing the exception in Catch block
' but still the following code will be executed
If conn IsNot Nothing AndAlso _
conn.State = ConnectionState.Open Then
' if connection was established then close it
conn.Close()
End If
' =====================-------------------------
End Try
' this line however will NOT be executed if
' exception is occurred
Debug.Print("Outside the Try..Catch block")
End Sub
As you can see this method will be inserting data in 2 tables. Our goal is,
Begin the Transaction
Try to Insert the Data in Tables
If no error occurs on Insertion then Commit the Transaction
If error occurred then
Rollback the Transaction
Again throw the Exception (so the caller is being notified)
End If
At the end (whether exception is occred or NOT) Close the connection
Note that if Exception occurs then in Catch block we are throwing the same exception again. At this point it seems that control will immediately exit from this method, but fortunately this does NOT happen in this way. Instead control first jumps to Finally block then after that it exits from method.
Enter Key to Set Focus in Next Control (for Data Entry Forms)
Level: Beginner
Knowledge Required:
Windows Forms
Description:
In a Windows Application, we use Tab key to move Focus from current control to next control, but in a Data Entry applications, usually Enter Key is used for this purpose.
There are different techniques to accomplish this. I think the following is the simplest one.
First set the Form's KeyPreview property to True. Then put the following code in the KeyPress Event Handler:
Knowledge Required:
Windows Forms
Description:
In a Windows Application, we use Tab key to move Focus from current control to next control, but in a Data Entry applications, usually Enter Key is used for this purpose.
There are different techniques to accomplish this. I think the following is the simplest one.
First set the Form's KeyPreview property to True. Then put the following code in the KeyPress Event Handler:
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = Chr(Keys.Return) Then
Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
End If
End Sub
Tuesday, July 29, 2008
Implement SQLCommand Cancel with Threading
Level: Advanced
Knowledge Required:
In a data driven application, sometimes we built queries which take time. In these type of scenarios usually developers put the query execution on different thread, so the User Interface keep responsive.
A more user friendly applications provide a flexibility to cancel the currently executing command. This can be achieved by using SQLCommand.Cancel() method.
So to implement it,
The above method just executes a WAITFOR DELAY query which simulates a very long query that takes 5 seconds to complete. Note that objCon and objCmd are Module Level variables. This method will be executed in a different thread using the following code,
While this query is being executed we will perform a query cancel on a button click event as,
See Also:
Asynchronous Data Loading using TableAdapter with Cancel Feature
Knowledge Required:
- ADO.net
- Threading
In a data driven application, sometimes we built queries which take time. In these type of scenarios usually developers put the query execution on different thread, so the User Interface keep responsive.
A more user friendly applications provide a flexibility to cancel the currently executing command. This can be achieved by using SQLCommand.Cancel() method.
So to implement it,
- Create a Thread
- Execute Query in that Thread
- Meanwhile if user clicks the Cancel button we will call the SQLCommand.Cancel method
Private Sub DoSomeWork()
objCon = New SqlConnection("Data Source=.;Integrated Security=True")
objCmd = New SqlCommand("WAITFOR DELAY '00:00:05';", objCon)
objCon.Open()
Try
objCmd.ExecuteReader()
Catch ex As SqlException
Debug.Print(ex.Message)
End Try
objCon.Close()
End Sub
The above method just executes a WAITFOR DELAY query which simulates a very long query that takes 5 seconds to complete. Note that objCon and objCmd are Module Level variables. This method will be executed in a different thread using the following code,
Dim t As Threading.Thread
t = New Threading.Thread(AddressOf DoSomeWork)
t.Start()
While this query is being executed we will perform a query cancel on a button click event as,
Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
If objCmd IsNot Nothing Then
objCmd.Cancel()
End If
End Sub
See Also:
Asynchronous Data Loading using TableAdapter with Cancel Feature
Monday, July 28, 2008
Draw Focus Rectangle using ControlPaint Class
Level: Beginner
Knowledge Required:
GDI+
Description:
Sometimes while creating a User Control from scratch. It is required to display the Focus Rectangle (the dotted border). This can be easily achieved by using
System.Windows.Forms.ControlPaint
E.g.:
ControlPaint class contains other useful routines for control drawing you can explore the list using intellisense.
Knowledge Required:
GDI+
Description:
Sometimes while creating a User Control from scratch. It is required to display the Focus Rectangle (the dotted border). This can be easily achieved by using
System.Windows.Forms.ControlPaint
E.g.:
Private Sub Form1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Click
Dim g As Graphics
g = Me.CreateGraphics
ControlPaint.DrawFocusRectangle(g, New Rectangle(10, 10, 100, 100))
End Sub
ControlPaint class contains other useful routines for control drawing you can explore the list using intellisense.
Saturday, July 26, 2008
Dynamically Loading Data in TreeView control ASP.net
Level: Beginner
Knowledge Required:
- ASP.net
- Typed DataSet
- TableAdapter
- SQL Server 2005
Thursday, July 17, 2008
Replace with Regular Expression
This article explains some outstanding usage of Regular Expression's Replace Method
Level: Intermediate
Knowledge Required:
Regular Expressions
Description:
Currently I am working on a Tool (Short Project) to convert the code into HTML. This is my requirement, since it takes time to convert the code into HTML format, before I can paste into Blogger.
So I will be heavily using Regular Expression (RegEx Class) in this project. Meanwhile I am sharing the core technique here.
In code we use Keywords, words that highlight with different color. For example "Dim", "Me", "As", "For", etc. I use "span" or "font" tag to change the text color. E.g.
<span style="color:blue;">Dim</span>
Usually keywords found to be separated with white-spaces,
Dim myVar As String
3 Keywords: Dim, As, String
All of them are separated with Space. But some keywords are used as Instances,
Me.TextBox1.Text = "ABC"
Here "Me" has "." (full stop)
As per above findings, I decided,
Me.TextBox1.Text = "ABC"
we can replace the above line as,
<span style="color:blue;">Me</span>.TextBox1.Text = "ABC"
So here we are using the Replace. Which gave me the idea to use the Regular Expression, because its Replace method is very flexible. First we need to decide the Pattern. For the above case the pattern will be,
(\W|^)(Me)(\W|$)
In above statement () brackets are indicating Groups. Therefore in above pattern I have used 3 groups. Which we will be using in Replace String.
Next we need to decide what should be the Replace String.
$1<font color=blue>$2</font>$3
The above string means that while replacing,
1) Put Group #1
2) Put Font Tag
3) Put Group #2
4) Close the Font Tag
5) Put the Group #3
That's it, here is the complete code,
Level: Intermediate
Knowledge Required:
Regular Expressions
Description:
Currently I am working on a Tool (Short Project) to convert the code into HTML. This is my requirement, since it takes time to convert the code into HTML format, before I can paste into Blogger.
So I will be heavily using Regular Expression (RegEx Class) in this project. Meanwhile I am sharing the core technique here.
In code we use Keywords, words that highlight with different color. For example "Dim", "Me", "As", "For", etc. I use "span" or "font" tag to change the text color. E.g.
<span style="color:blue;">Dim</span>
Usually keywords found to be separated with white-spaces,
Dim myVar As String
3 Keywords: Dim, As, String
All of them are separated with Space. But some keywords are used as Instances,
Me.TextBox1.Text = "ABC"
Here "Me" has "." (full stop)
As per above findings, I decided,
To Convert the Code into HTML replace the Keywords with the Tags
Me.TextBox1.Text = "ABC"
we can replace the above line as,
<span style="color:blue;">Me</span>.TextBox1.Text = "ABC"
So here we are using the Replace. Which gave me the idea to use the Regular Expression, because its Replace method is very flexible. First we need to decide the Pattern. For the above case the pattern will be,
(\W|^)(Me)(\W|$)
In above statement () brackets are indicating Groups. Therefore in above pattern I have used 3 groups. Which we will be using in Replace String.
Next we need to decide what should be the Replace String.
$1<font color=blue>$2</font>$3
The above string means that while replacing,
1) Put Group #1
2) Put Font Tag
3) Put Group #2
4) Close the Font Tag
5) Put the Group #3
That's it, here is the complete code,
Dim sCode As String
Dim sHTML As String
sCode = "Me.TextBox1.Text=""Abc"""
sHTML = System. _
Text. _
RegularExpressions. _
Regex.Replace( _
sCode, _
"(\W|^)(Me)(\W|$)", _
"$1<font color=blue>$2</font>$3", _
System.Text.RegularExpressions.RegexOptions.IgnoreCase _
)
Debug.Print(sHTML)
Wednesday, July 16, 2008
How to Pass Data Across Forms
In this post we will discuss how can we share different variables among Forms.
Level: Beginner
Knowledge Required:
Win Forms
Description:
While creating a Windows Forms Application, we usually face a requirement when we need to pass one or more variables from one Form to another. For example, we have created a Dialog Box which takes Date Range,

When we display this dialog box, we want that a default date range should be given, also this dialog box should return the new Date Range that is selected.
To pass the data to Form we can directly use Form's Control as,
In Form1.Button1.Click Event Handler:
DateRangeDialog.DateTimePicker1.Value = Now
As you can see the above code, I have used the DateRangeDialog's DateTimePicker control in Form1's Button Click event Handler, but it is better to create Public Properties on Form and use them. Also we can utilize the Constructor (New Method).
Usage:
Level: Beginner
Knowledge Required:
Win Forms
Description:
While creating a Windows Forms Application, we usually face a requirement when we need to pass one or more variables from one Form to another. For example, we have created a Dialog Box which takes Date Range,

When we display this dialog box, we want that a default date range should be given, also this dialog box should return the new Date Range that is selected.
To pass the data to Form we can directly use Form's Control as,
In Form1.Button1.Click Event Handler:
DateRangeDialog.DateTimePicker1.Value = Now
As you can see the above code, I have used the DateRangeDialog's DateTimePicker control in Form1's Button Click event Handler, but it is better to create Public Properties on Form and use them. Also we can utilize the Constructor (New Method).
Public Class dlgDateRange
Private _DateStart As Date
Private _DateEnd As Date
'Public properties that will be used to get the selected dates
Public ReadOnly Property DateStart() As Date
Get
Return Me._DateStart
End Get
End Property
Public ReadOnly Property DateEnd() As Date
Get
Return Me._DateEnd
End Get
End Property
' default constructor
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me._DateStart = Now
Me._DateEnd = Now
End Sub
' if dates are supplied on initializing
Public Sub New(ByVal DateStart As Date, ByVal DateEnd As Date)
Me.New()
' Add any initialization after the InitializeComponent() call.
Me._DateStart = DateStart
Me._DateEnd = DateEnd
End Sub
' OK button is clicked
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
' set the selected values and close dialog
Me._DateStart = Me.DateTimePicker1.Value
Me._DateEnd = Me.DateTimePicker2.Value
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub
' cancel button is clicked
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
' on form load event we will set the dates which were supplied on initializing
Private Sub dlgDateRange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.DateTimePicker1.Value = Me._DateStart
Me.DateTimePicker2.Value = Me._DateEnd
End Sub
End Class
Usage:
Dim dlgNew As dlgDateRange
dlgNew = New dlgDateRange(New Date(2008, 1, 1), New Date(2008, 6, 30))
If dlgNew.ShowDialog() = Windows.Forms.DialogResult.OK Then
Debug.Print("Date Start: " & dlgNew.DateStart)
Debug.Print("Date End: " & dlgNew.DateEnd)
End If
Monday, July 14, 2008
Custom Tab Control Layout
Level: Intermediate
Knowledge Required:- Tab Control
- GDI+
So first we are going to change its alignment to Left, by setting the property:
Alignment = Left
If you have XP themes turned on then you may notice the weird layout of Tab Control. Don't worry we will make it fine.
As you may have noticed that Tabs are vertical, and our requirement is horizontal. So we can change the size of Tabs. But before we can do this we have to set the SizeMode property as,
SizeMode = Fixed
Now we can change the size by using the ItemSize property,
ItemSize = 30, 120
Width = 30 and Height = 120
After setting the Alignment = Left, Tab control rotates the Tabs which causes the Width and Height seem to be reversed. That is why when we increase Height, we see that width is increasing and when we increase width the height is effected.
Now Text will also be displaying, but vertically. Unfortunately there is no simple way to resolve this issue. For this purpose we have to write the Text by ourselves. To do this we will first set the DrawMode
DrawMode = OwnerDrawFixed
Now its our job to display the Text on Tabs. Since we have set the DrawMode property = OwnerDrawFixed, therefore we can use the DrawItem event as,
Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem Dim g As Graphics Dim sText As String Dim iX As Integer Dim iY As Integer Dim sizeText As SizeF Dim ctlTab As TabControl ctlTab = CType(sender, TabControl) g = e.Graphics sText = ctlTab.TabPages(e.Index).Text sizeText = g.MeasureString(sText, ctlTab.Font) iX = e.Bounds.Left + 6 iY = e.Bounds.Top + (e.Bounds.Height - sizeText.Height) / 2 g.DrawString(sText, ctlTab.Font, Brushes.Black, iX, iY) End SubDownload Source: CustomTabControlLayout.zip
Customized Tab Control
Level: Intermediate
Knowledge Required:- Custom Controls
- Tab Control
- Inheritance
- GDI+
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True) Me.SetStyle(ControlStyles.UserPaint, True)The 2nd line tells the Tab Control NOT to use its own Control Drawing, instead use the OnPaint method to draw the contents of control. Note that the Tab Pages will be rendered by themselves, we don't need to handle them. In the OnPaint Method we will perform as, 1) Create the Background of Tab Control 2) Draw the Tab Buttons For drawing the Tab Buttons we will use the GetTabRect() method, which returns the bounds of Tab Button to be displayed. That is the core customization. Additionally I have added other properties,
| Properties | Description |
| BackColor | Control's background color |
| HeaderWidth | Width of Tab Buttons |
| HeaderHeight | Height of Tab Buttons |
| HeaderAlignment | Text Alignment in the Tab Button |
| HeaderPadding | Padding of Text in the Tab Button |
| HeaderBorderColor | Tab Button Border Color |
| HeaderFont | Font of Tab Button |
| HeaderBackColor | Background Color of Tab Button |
| HeaderForeColor | Text Color of Tab Button |
| HeaderSelectedBackColor | Background color of Selected Tab Button |
| HeaderSelectedForeColor | Text Color of Selected Tab Button |
Subscribe to:
Posts (Atom)