Sunday, January 12, 2014

ComboBox With AutoComplete TextBox In VB.NET

Most of the developers are familiar with the auto completion text feature available in browsers, search controls and other controls. The auto completion feature is when you start typing some characters in a control; the matching items are loaded automatically for you. 

In Windows Forms 2.0 or later versions (
Visual Studio 2005 or later versions), some of the controls support this feature including the ComboBox and the TextBox controls. By using these features, we can build Google search like auto completion functionality in our Windows Forms applications.
For example, we can have a ComboBox control that completes URLs as soon as you type any character. For example, in Figure 1, I typed "c-s" and I see all the URLs starting with "c-s".
 

The AutoCompleteSource and AutoCompleteMode properties of the TextBox and ComboBox controls allow developers to provide automatic completion text feature. You can set both of these properties at design-time as well as at run-time. If you click on AutoCompleteSource drop down, you will see all the options in the drop-down list. See Figure 2.

 
Figure 3 shows AutoCompleteMode options.
You can also set these properties at run-time using the following code:  
comboBox1.AutoCompleteSource = AutoCompleteSource.AllSystemSources
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
The AutoCompleteSource Enumeration has following members:
  • AllSystemResources - Specifies the equivalent of FileSystem and AllUrl as the source. This is the default value when AutoCompleteMode has been set to a value other than the default.
  • AllUrl - Specifies the equivalent of HistoryList and RecentlyUsedList as the source.
  • CustomSource - Specifies strings from a built-in AutoCompleteStringCollection as the source.
  • FileSystem - Specifies the file system as the source. 
  • FileSystemDirectories - Specifies that only directory names and not file names will be automatically completed.
  • HistoryList - Includes the Uniform Resource Locators (URLs) in the history list.
  • ListItems - Specifies that the items of the ComboBox represent the source.
  • None - Specifies that no AutoCompleteSource is currently in use. This is the default value of AutoCompleteSource.
  • RecentlyUsedList - Includes the Uniform Resource Locators (URLs) in the list of those URLs most recently used.
The AutoCompleteMode enumeration has following members:
  • Append - Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters.
  • None - Disables the automatic completion feature for the ComboBox and TextBox controls.
  • Suggest - Displays the auxiliary drop-down list associated with the edit control. This drop-down is populated with one or more suggested completion strings.
  • SuggestAppend - Applies both Suggest and Append options.
Loading Custom Source 
We can also specify a custom source from where the listing will be loaded. If you click on the AutoCompleteCustomSource property, it will open the String Collection Editor, where we can add our strings. For example, I add following strings to the strings list. See Figure 4.
Now we need to set AutoCompleteSource to CustomSource and AutoCompleteMode to Suggest.

And when I run the application and type "m" in the ComboBox, I see output that looks like Figure 5. As you can see from Figure 5, all author names starting with letter m are listed in the list.


We can also create AutoCompleteStringCollection programmatically. The following code creates an AutoCompleteStringCollection, adds strings to the collection, and sets it to the AutoCompleteCustomSource of the ComboBox. 
' Create a string collection
        Dim authors As New AutoCompleteStringCollection
        authors.Add(" Mike Gold")
        authors.Add(" Praveen Kumar")
        authors.Add(" Mahesh Chand")
        authors.Add(" Michelle Ronald")
        authors.Add(" Mayor Rogers")
        authors.Add(" Raj Beniwal")
        authors.Add(" Dinesh Beniwal")
        authors.Add(" Neel Beniwal")
        authors.Add(" Nipun Tomar")

        ' Set ComboBox AutoComplete properties
        ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
        ComboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
        ComboBox1.AutoCompleteCustomSource = authors

Summary
The AutoComplete feature of ComboBox and TextBox controls allow us to set the auto complete text feature. In this article, we saw how to use this feature in our application at design-time as well as at run-time.

Wednesday, January 08, 2014

How to convert DataGridView DataTable / DataGrid to DataTable



How to convert DataGridView DataTable


private DataTable ToDataTableASM(DataGridView dataGridView, string tableName)
        {
            DataGridView dgv = dataGridView;
            DataTable table = new DataTable(tableName);

            // Create  columnas
            for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
            {  
                    table.Columns.Add(dgv.Columns[iCol].Name);
            }

            /* THIS WORKS  DataGrid to DataTable... */

            foreach (DataGridViewRow row in dgv.Rows)
            {
                DataRow datarw = table.NewRow();
                for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
                {
                    try
                    {
                        datarw[iCol] = row.Cells[iCol].Value;
                    }
                    catch (Exception ex)
                    { }
                }

                table.Rows.Add(datarw);
            }
            return table;
        }

کون اس راہ سے گزرتا ہے

کون اس راہ سے گزرتا ہے
دل یونہی انتظار کرتا ہے

ہم تو چُپ چاپ چلے آئے بحکمِ حاکم
راستہ روتا رہا شہر سے ویرانے تک


رہیں گے چل کے کہیں اوراگر یہاں نہ رہے
بَلا سے اپنی جو آباد گُلسِتاں نہ رہے

ہم ایک لمحہ بھی خوش زیرِ آسماں نہ رہے
غنِیمت اِس کوسَمَجْھیے کہ جاوِداں نہ رہے

Tuesday, January 07, 2014

The Tortoise Trainer painted by Osman Hamdi Bey

The Tortoise Trainer (Turkish: Kaplumbağa Terbiyecisi) is a painting painted by Osman Hamdi Bey in 1906 and 1907 (two versions). In 2004 it was sold for $3.5M. famous Turkish painter at the time in the Ottoman Empire.
The painting depicts an elderly man in traditional Ottoman religious costume dating from before introduction of the fez and spread of western style dress in the latter part of the 19th century. He holds a traditional "nay" flute with which he is attempting to "train" the tortoises at his feet.
Hamdi Bey created the painting at a time of great social and political upheaval in the Ottoman Empire. The reforms introduced by Sultan Abdul Hamid II (22 September 1842 – 10 February 1918) had either proved ineffective or had been reneged upon having themselves been blamed for the increased upheaval.
The Ottoman empire, which still encompassed parts of Greece and the south Balkans as well as the Levant and much of the Arab peninsula was under serious threat both from the growing power of nationalist movements and from incursion by the foreign powers which would eventually divide the empire between them in the aftermath of WW1. The painting cleverly satirises the slow and ineffective attempts at reforming the Ottoman Empire as the attempts of an anachronistic historical character to train tortoises.
Although not widely shown or understood at the time time the painting achieved greater significance in subsequent decades as it presaged the Young Turk Revolution of 1908 which brought and end to the direct autocratic rule of the empire by the Sultan and set the stage for the Empire's entry into WW1 on the side of Germany and Austria Hungary and for its subsequent break up.

 Artist    Osman Hamdi Bey
Year    1906

References

The Tortoise Trainer

Wednesday, January 01, 2014

Validation Using Regular Expressions on c# windows form

Regular expressions are great way to validate data provided by a user to the fields of a form. Suppose that a user should input an age rather than a name, or an address rather than a gender, you can use power of regular expressions to validate them. The following example creates a simple windows forms application that demonstrates the use of regular expression in validating each fields of a form. Create a new windows forms application and add the below Textbox as per given label names.

LabelTypeNameProperty Values
1TextBoxfirstNameTextBox
2TextBoxlastNameTextBox
3TextBoxageTextBox
4TextBoxgenderTextBox
5TextBoxaddressTextBox
6TextBoxzipCodeTextBox
7ButtonsubmitButtonTextSubmit

 Although we can use radio buttons for the Gender field, we will be using a text box to demonstrate validation of text using regular expressions. Double click the submitButton to generate an event handler for its Click event. Be sure to import System.Text for the StringBuilder class that we will use andSystem.Text.RegularExpressions for the Regex class.

using System.Text;
using System.Text.RegularExpressions;

We should also declare a StringBuilder and Regex members in our Program class.
private StringBuilder errors;
private Regex validator;
 Use the following code for the Click event handler of submitButton.
private void submitButton_Click(object sender, EventArgs e)
{
    if (AreFieldsValid())
    {
        //Do task here
    }
}
The following is the code for AreFieldsValid() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private bool AreFieldsValid()
{
    errors = new StringBuilder();
 
    //Validate First Name and Last Name
    validator = new Regex(@"^([A-Z][a-z]+)(\s[A-Z][a-z]+)*$");
 
    if (!validator.Match(firstNameTextBox.Text).Success)
        errors.AppendLine("First name is not in the proper format.");
 
    if (!validator.Match(lastNameTextBox.Text).Success)
        errors.AppendLine("Last name is not in the proper format.");
 
    //Validate Age
    validator = new Regex(@"^\d{1,2}$");
 
    if (!validator.IsMatch(ageTextBox.Text))
        errors.AppendLine("Invalid Age.");
 
    //Validate Gender
    validator = new Regex(@"^([M|m]ale|[F|f]emale)$");
 
    if (!validator.IsMatch(genderTextBox.Text))
        errors.AppendLine("Invalid Gender.");
 
    //Validate Address
    validator = new Regex(@"^[0-9]+(\s[a-zA-Z]+)+$");
 
    if (!validator.IsMatch(addressTextBox.Text))
        errors.AppendLine("Address is not in the proper format.");
 
    //Validate ZipCode
    validator = new Regex(@"^\d{4}$");
 
    if (!validator.IsMatch(zipCodeTextBox.Text))
        errors.AppendLine("Invalid zip code");
 
    if (errors.ToString() == String.Empty)
    {
        return true;
    }
    else
    {
        MessageBox.Show(errors.ToString(), "Validation Failed", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
 
        return false;
    }
}