Pages

Monday, June 21, 2010

AutoComplete TextBox or ComboBox in Winforms using C#

AutoComplete TextBox or ComboBox in Winforms

In my previous article Implementing autocomplete textbox in gridview using Ajax autocomplete extender i explained how to create AutoComplete TextBox in ASP .NET using AJAX , in this example i am achieving the same in Windows forms application


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





Properties of TextBox that needs to be set


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


C# Code


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




Source : http://www.dotnetfunda.com/articles/article225.aspx

No comments: