Tuesday, March 23, 2010

Creating winforms AutoComplete TextBox using C# in Windows application

In This Example I explain You how to create a AutoComplete TextBox In windows forms application using C#.



Here Are two way We can Use

-Auto complete textBox with previously entered text in textbox.

-AutoComplete textBox by fetching the data from database.

First of all create a global AutoCompleteStringCollection

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;
}
}
}


THis Is Second Method



AutoComplete textBox by fetching the data from database.

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

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");
}

}
}