MY PRINCIPAL :- "THE GLORY OF LIFE ID TO LOVE NOT TO BELOVED...TO GIVE NOT TO GET..TO SERVE NOT TO BE SERVED."

Wednesday, November 17, 2010

AutoComplete TextBox In C#(Windows Application)

Hello Guys...
 As we know we are basically dealing with web applications and desktop application in our day to day life...
 So my todays topic is to provide the autocomplete facility to the textbox in windows application. We always deal this type of thing in web application...but we can also implement this kind of thing in our windows application

Here we are.....

Design:





Coding:


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;
using System.Data;

namespace AutocompleteTextbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = @"Data Source=datasourcename;Initial Catalog=Northwind;Persist Security       Info=True;User ID=sa;Password=123";
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select ContactName from Customers";
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            con.Close();
            AutoCompleteStringCollection local = new AutoCompleteStringCollection();
            if(dt.Rows.Count>=0)
            {
                for (int count = 0; count < dt.Rows.Count; count++)
                {
                    local.Add(dt.Rows[count]["ContactName"].ToString());

                }
            }
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox1.AutoCompleteCustomSource = local;


        }
}

Explanation:

    
1.    AutoCompleteStringCollection: This allows us to make the collection for our textbox to bind. After getting the data from database we have add that data to this collection.

2.    AutoCompleteMode : Gets or sets an option that controls how automatic completion works for the textbox.

3.   .AutoCompleteSource:Gets or sets a value specifying the source of complete strings used for automatic completion.

4.    AutoCompleteCustomSource:Gets or sets a custom System.collections.specialized.stringcollection to use when the AutoCompleteSource property is set to CustomSource.


Happy coding.....

No comments:

Post a Comment