Tuesday, January 13, 2009

Creating winforms AutoComplete TextBox using C# in Windows application


In this example i am explaining how to create a AutoComplete TextBox In windows forms application using C#.

If you are looking for Autocomplete textbox in ASP.NET web/ aspx pages than read this article
Ajax autocomplete extender textbox in EditItemTemaplate of GridView

There are two ways we can use Autocomplete feature

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

2. AutoComplete textBox by fetching the data from database.


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 attached




www.tips-fb.com
Shout it
Stumble Upon Toolbar
Submit this story to DotNetKicks vote it on WebDevVote.com add to del.icio.us saved by 0 users
Subscribe to Feeds

19 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
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
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
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??


About Me

My Photo
amiT jaiN
Hi, I am amiT jaiN Software engineer working on C#.NET and ASP.NET technologies
View my complete profile

Comments

.NET Resources

Find More Articles


Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer


C#.NET Articles and tutorials,ASP.NET Articles - blog by amiT jaiN