简体   繁体   中英

Auto complete in datagridview in C#

I've been searching for an answer for my question everywhere. But I couldn't find a satisfactory answer yet. Now here's my problem.

I have a datagridview in C# which is unbound to any data source. I want to let the user to enter data in one of the columns. What I need to do is to support the user with autocomplete.

The data for auto complete comes from a database. I could well handle this but my problem is that the suggestions should depend on the characters entered by the user. For an example if the user enters 'g' and my database query returns 'garlic', the auto complete should show it.

This is quite easy for normal textboxes. But the problem with datagridview is that I cannot read the characters users enter as they type in. The cell value changed event fires after the editing is complete. The data in the database is too much to be added to the autocomplete source at once. So I have to resolve to get what the user type and generate the source according to that.

Is there any way that I could achieve this task? Please help.

Below is one of the codes that I recently used but to no avail, it does not do the job:

 private void Form2_Load(object sender, EventArgs e)
        {

            string str = @"Data Source=MEDIXPC197;Initial Catalog=Inventory;Integrated Security=True";
            SqlConnection con = new SqlConnection(str);
            SqlDataAdapter da = new SqlDataAdapter("SELECT Product Code from tblmaster", con);
            dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
}

 private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            string text = dataGridView1.Columns[4].HeaderText;
            if (text.Equals("Product Code")) ;
            {
                TextBox auto_text = e.Control as TextBox;
                if (auto_text != null)
                {
                    auto_text.AutoCompleteMode = AutoCompleteMode.Suggest;
                    auto_text.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    AutoCompleteStringCollection sc = new AutoCompleteStringCollection();
                    add_items(sc);
                    auto_text.AutoCompleteCustomSource = sc;
                }
            }

        }
        public void add_items(AutoCompleteStringCollection column)
        {
            column.Add("test1");

EDIT:

I have already made it work using other code(see below) and now my problem is that the suggestion only shows if the letter that I typed is the first letter of the data being shown from the database, I need something that when I type something, for example, I typed 1, the suggestion will show "1, typo1, tester1tester, 111"

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private void Form1_Load(object sender, EventArgs e)
        {

            //Left = (MdiParent.ClientRectangle.Width - Width) / 2;
            //Top = (MdiParent.ClientRectangle.Height - Height) / 2;

            DataGridViewTextBoxColumn dgvslno = new DataGridViewTextBoxColumn();
            dgvslno.HeaderText = "Item Code";
            dgvslno.Width = 40;
            dataGridView1.Columns.Add(dgvslno);

            DataGridViewTextBoxColumn dgvpro = new DataGridViewTextBoxColumn();
            dgvpro.HeaderText = "Product Name";
            dgvpro.Width = 40;
            dataGridView1.Columns.Add(dgvpro);
        }

        public AutoCompleteStringCollection AutoCompleteLoad()
        {
            SqlConnection conn = new SqlConnection(@"Data Source=MEDIXPC197;Initial Catalog=Inventory;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select ProductCode from tblmaster", conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            AutoCompleteStringCollection mycoll = new AutoCompleteStringCollection();
            while (dr.Read())
            {
                mycoll.Add(dr["ProductCode"].ToString());
            }
            return mycoll;
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int column = dataGridView1.CurrentCell.ColumnIndex;
            string headerText = dataGridView1.Columns[column].HeaderText;

            if (headerText.Equals("Item Code"))
            {
                TextBox tb = e.Control as TextBox;

                if(tb != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteCustomSource = AutoCompleteLoad();
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
            else
            {
                TextBox tb = e.Control as TextBox;
                if (tb !=null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.None;
                }
            }
        }
    }
}

I have already made it work using other code(see below) and now my problem is that the suggestion only shows if the letter that I typed is the first letter of the data being shown from the database, I need something that when I type something, for example, I typed 1, the suggestion will show "1, typo1, tester1tester, 111"

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private void Form1_Load(object sender, EventArgs e)
        {

            //Left = (MdiParent.ClientRectangle.Width - Width) / 2;
            //Top = (MdiParent.ClientRectangle.Height - Height) / 2;

            DataGridViewTextBoxColumn dgvslno = new DataGridViewTextBoxColumn();
            dgvslno.HeaderText = "Item Code";
            dgvslno.Width = 40;
            dataGridView1.Columns.Add(dgvslno);

            DataGridViewTextBoxColumn dgvpro = new DataGridViewTextBoxColumn();
            dgvpro.HeaderText = "Product Name";
            dgvpro.Width = 40;
            dataGridView1.Columns.Add(dgvpro);
        }

        public AutoCompleteStringCollection AutoCompleteLoad()
        {
            SqlConnection conn = new SqlConnection(@"Data Source=MEDIXPC197;Initial Catalog=Inventory;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select ProductCode from tblmaster", conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            AutoCompleteStringCollection mycoll = new AutoCompleteStringCollection();
            while (dr.Read())
            {
                mycoll.Add(dr["ProductCode"].ToString());
            }
            return mycoll;
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int column = dataGridView1.CurrentCell.ColumnIndex;
            string headerText = dataGridView1.Columns[column].HeaderText;

            if (headerText.Equals("Item Code"))
            {
                TextBox tb = e.Control as TextBox;

                if(tb != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteCustomSource = AutoCompleteLoad();
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
            else
            {
                TextBox tb = e.Control as TextBox;
                if (tb !=null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.None;
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM