首页 > 解决方案 > Filling textbox when autofill text box selected index changed in C# windows form

问题描述

I just want to fill the other textbox when user selected an string from the autofill textbox1 i am using this code for autofill a textbox.

private void frmHistory_Load(object sender, EventArgs e)
{
    try
    {           
        string query = "select ID  from Customer ";
        SqlCommand cmd = new SqlCommand(query,con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        AutoCompleteStringCollection mycollection = new AutoCompleteStringCollection();
        while(dr.Read())
        {
            mycollection.Add(dr.GetInt32(0).ToString());
        }
        textBox1.AutoCompleteCustomSource = mycollection;     
        con.Close();                
    }
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    }
}

标签: c#

解决方案


没有用于选择自动填充的事件。大多数人所做的就是检测是否点击了ENTER键。我建议还检测 TAB 键并处理该PreviewKeyDown事件:

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyData == Keys.Enter || e.KeyData == Keys.Tab)
    {
        textBox2.Text = textBox1.Text;
    }
}

推荐阅读