Sunday, February 24, 2008

AutoCompleteMode TextBox

Hey Guys!!

Today I thought I shall give you a slight introduction about the possibilities of the AutoCompleteMode property of TextBoxes.

This is the property which helps in displaying the words similar to the one we are typing in the textbox in a dropdown below.Normally we see this feature while trying to login or so in any webpage.There are ofcourse other places were we can use this feature.

Today we shall see how to display the usernames similar to the one being typed in the textbox right below the textbox.We are using a MySQLConnection for the same.

To start with,

Place a textbox on a form and set its properties,

AutoCompleteMode to Suggest
and
AutoCompleteSource to CustomSource

Now as usual we require the connection,command and all to retrieve the data from MySQL

MySQL.Data.MySqlClient.MySqlDataReader read;

comm.Connection = connect;

comm.CommandText = "select * from users";
BindingSource bSource = new BindingSource();
read = com.ExecuteReader();
bSource.DataSource = read;
read.Close();

string usernameField = "username";//the field name from table
AutoCompleteStringCollection filterUsers = new AutoCompleteStringCollection();
foreach (object userItem in bSource.List)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(userItem);
PropertyDescriptor propDesc = props.Find(usernameField, true);
string fieldUserVal = propDesc.GetValue(userItem).ToString();
filterUsers.Add(fieldUserVal);
}

_searchTermUserText.AutoCompleteCustomSource = filterUsers;

This does the job.

Its very simple.We get the collection of fields from the bSource one row at a time.
Then filter just the username field from that and get the value of the field in this row.

We append each of these obtained values one by one to our string collection.Finally add that to the textbox.

I hope you were able to understand the things that I explained.

So...bye for now...Will come back soon with something more exciting. :)

Cheers....

No comments: