Thursday, 28 November 2013

How to create AutoCompleteTextBox in Windows Application

How to create AutoCompleteTextBox in Windows Application………………………..

Note: AutoCompleteTextBox means  it gives full hits of the coming text

//This query execute in Sql Server 2008 for create database and table…………..

create database Autocomplete
create table tbl_autocomplete(id int identity(1,1) primary key,name nvarchar(50) unique)

After execute this query We take one Windows Application as the picture is given below we create  a Windows Form just like the picture……………….


//This source code  for  Form1.cs……………………..

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;

namespace AutoCompleteTextBox_Windows
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//call this method here
AutoComplete();
}

SqlConnection con = new SqlConnection("Data Source=KUSH-PC\\KUSH;Initial Catalog=Autocomplete;User ID=sa;Password=tiwari");
SqlCommand cmd;
//code for create method TextBox with AutoComplete ....................................
void AutoComplete()
{
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
cmd = new SqlCommand("select * from tbl_autocomplete", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//string s = "name";
string name = rdr.GetString(1);
col.Add(name);
}
con.Close();
textBox1.AutoCompleteCustomSource = col;

}

// code for when you insert any word
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tbl_autocomplete where name like '" + textBox1.Text + "'", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
}

}
}

 Result………………………………………..

1 comments: