AutoComplete TextBox In WinForms Windows Forms Application

In this example i am explaining how to create AutoComplete TextBox In WinForms Windows Forms Application Using C# VB.NET. There are two ways we can use Autocomplete feature

1. Auto complete with previously entered text in textbox.

2. AutoComplete TextBox by fetching data from database.

Read Ajax AutoComplete Extender Textbox for asp.net web applications.

1. Auto complete textBox with previously entered text in textbox.

For filling textbox with previously entered data/text in textbox using Autocomplete feature we can implement by setting autocomplete mode proeprty of textbox to suggest, append or sugestappend and setting autocomplete source to custom source progrmetically

First of all create a global AutoCompleteStringCollection and write code like this

namespace WindowsApplication1
{
public partial class Form1 : Form
{
AutoCompleteStringCollection autoComplete = new AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
autoComplete.Add(textBox1.Text);
MessageBox.Show("hello");
}

private void Form1_Load(object sender, EventArgs e)
{
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//auto.Add(textBox1.Text);
textBox1.AutoCompleteCustomSource = autoComplete;
}
}
}


2. AutoComplete textBox by fetching the data from database.

For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database

For autocomplete functionalty to work we need to define these 3 properties of textbox

1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory

2. AutoCompleteSource - this needs to be set as Custom Source

3. AutoCompleteCustomSource - this is the collection we created earlier

The complete C# code will look like this

namespace AutoCompleteTextBox
{

public partial class frmAuto : Form
{
public string strConnection =
ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection =
new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}

private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"Select distinct [Name] from [Names]" +
" order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());

}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();

txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;

}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show("Hope you like this example");
}

}
}

In the similar way we can also create a autocomplete type combobox

Download Sample Code


If you like this post than join us or share

38 comments:

최고를 위한 최선을 다하자 said...

good ! thank you!

using System.Windows.Form add ^^;

how to 2 nams?
AutoCompleteStringCollection namesCollection1 =
new AutoCompleteStringCollection();

AutoCompleteStringCollection namesCollection2 =
new AutoCompleteStringCollection();

??

thank you


BigOBig said...

Nice Coding Sir.. Thanking You

I am Using Like this also.. Use this function into Form pageload

private void GetLedgerList() // To Fill Ledger List To Ledger TextBox
{
errorProvider1.SetError(TxtLedger, "");

// Here I am getting Values From Database and Put in to Dataset
Dataset ds_Ledger = Ledger.GetLedgerList_ForAutoComplete();

if (ds_Ledger.Tables[0].Rows.Count <= 0) return;

var dt = ds_Ledger.Tables[0];
foreach (DataRow dr in dt.Rows)
{
namesCollection.Add(Convert.ToString(dr["DESCRIPTION"])); // Fill Items To TextBox Collection
}

TxtLedger.AutoCompleteMode = AutoCompleteMode.Suggest;
TxtLedger.AutoCompleteSource = AutoCompleteSource.CustomSource;
TxtLedger.AutoCompleteCustomSource = namesCollection;
}


Visual C# Kicks said...

Great information thanks


Anonymous said...

Thanks For Help


susmitha said...

i got an error while debugging Auto Complete textbox with previously entered text in textboxes.
error:The name 'auto' does not exist in this context.If i delete this line an exception is occuring at AutoCompleteMode.SuggestAppend saying textbox should be null.


amiT jaiN said...

hi susmitha:

Please gimme ur code so that i can look into the error and try to fix, paste ur code here


Anonymous said...

thanks
but if we are having some thousands of name starting with a letter and we just want some ten or twenty names to be appeared in our autocompletion list
How can we achieve this this ?


amiT jaiN said...

@Anonymous:

You can use TOP statement in that case

like

Select TOP 20 * from tablename


Ismail said...

Thanks for the article. I tried to download the file but could not, the file is not there anymore. Where from can i get the sample code?

Thnx Ismail


Zahid said...

Dear Sir What a greate Article and It Helped me a lot.
My Problme is, the text is shown in the TextBox but some field are missing from that Specific column. I mean some records of that column does not appeared in text hints. Please help me what should i do. I use the same code like in your article.


amiT jaiN said...

@Zahid:

Please check your sql statements whether they are returning results you want ?

Please provide me ur code so that i can look into ur problem


Anonymous said...

To: amiT jaiN
Thanks ... !! it's userful for me!


Anonymous said...

Thanks....but can i hav the sample code in a zip file??


Anonymous said...

Sir,

I have web form with next and previous button also i have database with few columns.When i click next button it read first row in
the database display sutabale data in the text boxes.when click next button again and again
data display row by row.when i click previous button, goback and read row and display sutable
details.pls send(rajith.hk@gmail.com) the code for this.


Anonymous said...

This really helped!! Thanks a lot Brother..

CJ


Anonymous said...

Excellent! Love this article!


Neelima said...

Hi,
Can anyone tell me how to use AutoCompleteStringCollection in web forms. It is working fine windows application, But I want same functionality in web form. Please help me out. As I am trying from longtime to solve this issue.

Thank You,
--Neeshika


Anonymous said...

upload another fule,please...


Rohit Jadhav said...

how to make auto-complete source comma seperated??


Anonymous said...

hi, can u make a tutorial on auto-completion textbox in smart device or windows mobile (like mobile dictionary with auto-completion functionality). I think some properties of textbox like autocompletemode, autocompletesource, etc. is not supported in windows mobile.

please email your tutorial at
barbzkie22@gmail.com
thanks


ankit said...

Hi Everyone,
This is very useful article,
Sir suppose If I am using a datagrid and bind this datagrid to database (Msaccess 2007)
then how can we do the similar thing in DatagridViewTextbox .


Anonymous said...

Hi Everyone,
This is very useful article,
Sir suppose If I am using a datagrid and bind this datagrid to database (Msaccess 2007)
then how can we do the similar thing in DatagridViewTextbox .


ankit said...

Hi Guys,
It is very useful article,
Here suppose I am using datagrid in place of textbox then how we write the code for datagrid cell.
Please help me Guys,


Adrian said...

Hi,
I desparatelly need the sample code project because i don't know how to implement this only with the source code posted on this blog!
Tried to download it but it always says: "This shared file or folder
link has been removed."
Please could anyone help me? :(


Anonymous said...

then code for datagridview ????


Vijay anand said...

Thanks for the useful article. Your site is really useful. Doing great job. Keep writing more!!!
Regards,
Present Technology


Anonymous said...

AutoComplete textBox by fetching the data from database.
No me reconoce "ConfigurationManager". You don't know cual podria ser mi problema?


Anonymous said...

it works, thats great
thank you


Anonymous said...

thanks,

this helped me too.
i have used this code in vb .net
it is working fine.

thanks once again


UR5FCM said...

Hello !
It's a very good job in vb.Net
But I'm have some trouble using autocomplete
I'm loading AutoCompleteStringCollection from big Text file
Then enter some chars in the textbox I'm periodicaly have Error: Memory not be read. Error Address 0x0000....

Please tell me how I'm resovle this problem
Thanks!


UR5FCM said...

Hello All !
Very good job usign AutoComplete TextBox in Vb.Net
I'm usign this option in my project
Before I'm load collection from big text file
Then enter letter on textbox i'm show list
Problem is what some time I'm see error: Memory ont be read by address 0x00000000....
What is happened I'm not understood!!
Please help me with this problem
Thanks!


Rohini Computers said...

Thanks a lot

thanks......


Anonymous said...

Nice Code Really i like your blog keep post new things

Regards
karthick


Anonymous said...

Does anyone have the source code that I could download?


Anonymous said...

Thanks for posting -
Got it to work w/ LINQ to SQL as well via:

using (var sourceDC = new SystemDataContext(ConnectionString))
{
var q = (from p in sourceDC.OrderLines select p.PONumber).Distinct().ToList();

if (q.Count > 0)
{
foreach(var poNumber in q)
namesCollection.Add(poNumber).ToString();

txtPONumber.AutoCompleteMode = AutoCompleteMode.Suggest;
txtPONumber.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtPONumber.AutoCompleteCustomSource = namesCollection;
}
}


Anonymous said...

Nice article, but download sample is not working :(


Anonymous said...

Hi,

Nice Article ... thanks for Posting....

Is it possible to display more conect in the suggestion? Like we are only displaying name here, but suppose with name we also want to display the age and location so we can identity them in case of dulplicate name. offcourse we can append them in a signle string but how to display the suggesions in grid like format.

thanks,
Ashish


joe said...

thank you so much the post was really helpful, will look forward for your post for any future reference :)


Find More Articles