Introduction
I had a trial before to write phone index program using VB6. I wanted to add twenty-six buttons to my form for alphabetical English characters A..Z (one button holds one character) to search for records in the database file of my phone index.
I found it easy because VB6 allows you to create an array of buttons or an array of any control.
When I wanted to re-write the same program using C# or VB.NET, I found the addition of twenty-six buttons to the form impractical because Visual Studio .NET does not have the same possibility as VB6 to create an array of controls.
In this article you will find it very easy to create an array of buttons, you can use this idea to create a tool for searching in database file.
I will write another article later to explain how to use this idea to search within the phone index as a database.
Background
I created two projects. I wrote code of one under C# (2003) and write another under VB.NET (2003). You can read my two projects which can be found in the download links at the top of this article.
Using the Code
C# Code
private void AddButtons()
{
int xPos = 0;
int yPos = 0;
System.Windows.Forms.Button[] btnArray = new System.Windows.Forms.Button[26];
for (int i = 0; i < 26; i++)
{
btnArray[i] = new System.Windows.Forms.Button();
}
int n = 0;
while(n < 26)
{
btnArray[n].Tag = n + 1;
btnArray[n].Width = 24;
btnArray[n].Height = 20;
if(n == 13)
{
xPos = 0;
yPos = 20;
}
btnArray[n].Left = xPos;
btnArray[n].Top = yPos;
pnlButtons.Controls.Add(btnArray[n]);
xPos = xPos + btnArray[n].Width;
btnArray[n].Text = ((char)(n + 65)).ToString();
btnArray[n].Click += new System.EventHandler(ClickButton);
n++;
}
btnAddButton.Enabled = false;
label1.Visible = true;
}
public void ClickButton(Object sender, System.EventArgs e)
{
Button btn = (Button) sender;
MessageBox.Show("You clicked character [" + btn.Text + "]");
}
VB Code
Private Sub AddButtons()
Dim xPos As Integer = 0
Dim yPos As Integer = 0
Dim n As Integer = 0
Dim btnArray(26) As System.Windows.Forms.Button
For i As Integer = 0 To 25
btnArray(i) = New System.Windows.Forms.Button
Next i
While (n < 26)
With (btnArray(n))
.Tag = n + 1
.Width = 24
.Height = 20
If (n = 13) Then
xPos = 0
yPos = 20
End If
.Top = yPos
pnlButtons.Controls.Add(btnArray(n))
xPos = xPos + .Width
AddHandler .Click, AddressOf Me.ClickButton
n += 1
End With
End While
btnAddButton.Enabled = False
label1.Visible = True
End Sub
Public Sub ClickButton(ByVal sender As Object, ByVal e As System.EventArgs) _
ndles MyBase.Click
Dim btn As Button = sender
MessageBox.Show("You clicked character [" + btn.Text + "]")
End Sub
Final Words
I hope this article is useful. If you have any ideas please tell me. Thanks to CodeProject and thanks to all.
Mostafa Kaisoun
m_kaisoun@hotmail.com