Sunday, October 25, 2009

Autocomplete textbox in C#

Here is the code to develop auto complete text box.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
private void Form1_Load(object sender, EventArgs e)
{
AutoCompleteStringCollection autolist = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();

SqlCommand comm = new SqlCommand("select * from users", con);
SqlDataAdapter da = new SqlDataAdapter(comm);

DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
autolist.Add(r[0].ToString());
}
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteCustomSource = autolist;
}

No comments:

Post a Comment