在列表中的Datagridview文本框自动完成搜索,不仅可以搜索首字母

时间:2018-12-13 06:23:02

标签: c# datagridview autocomplete

我的问题是,建议仅显示如果我键入的字母是数据库中显示的数据的第一个字母,我需要一些东西,例如,当我键入内容时,例如键入1,该建议将显示“ 1,typo1,tester1tester,111”

这是我用来在datagridview内的文本框中显示建议的代码:

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

    private void Form1_Load(object sender, EventArgs e)
        {
            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;
                }

0 个答案:

没有答案