【问题标题】:AutoComplete TextBox Control自动完成文本框控件
【发布时间】:2010-11-24 09:04:18
【问题描述】:

我想要一个文本框控件,它可以在使用 C# 2008 和 LINQ 的 Windows 应用程序中建议和附加数据库中的值。

我用组合框来做,但我不能用文本框来做。

我该怎么做?

【问题讨论】:

  • 对不起,我没有看到您使用的是 Windows 应用程序。

标签: c# winforms autocomplete


【解决方案1】:

您可以附加到 KeyDown 事件,然后在数据库中查询用户已经输入的那部分文本。例如,如果用户输入“T”,则搜索以“T”开头的事物。然后,当他们输入下一个字母(例如“e”)时,在表格中搜索以“Te”开头的内容。

例如,可用项目可以显示在“浮动”列表框中。您需要将 ListBox 放在 TextBox 下方,以便他们可以看到可用的条目,然后在他们完成输入后移除 ListBox。

【讨论】:

  • 编程的第一条规则:不要重新发明轮子;)
  • 是的。没有意识到有这个选项。我从来不做数据绑定。 (从 .Net 1.0 开始,当它们出现时尝试使用一些数据绑定功能,但发现它们限制太多。)
【解决方案2】:

查看AutoCompleteSourceAutoCompleteCustomSourceAutoCompleteMode 属性。

textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.Add("Foo");
col.Add("Bar");
textBox1.AutoCompleteCustomSource = col;

请注意,设计器允许您在不编写任何代码的情况下做到这一点...

【讨论】:

  • 我想从数据库中使用。你能帮帮我吗?我想从数据库中读取 Suggest 和 AutoComplete
  • @mohammad reza:您必须使用 ADO.net 编写代码才能访问 DB。
  • 只需在列表中填写您的查询结果
  • 我不知道如何通过我的查询来填充列表。我用 LINQ 写了一个查询
  • 如何在这个方法中设置Value & Text?例如:Text =“John Peter”,ID =“023”如果我选择“John Peter”如何在代码隐藏中获得“023”?
【解决方案3】:

当然这取决于你如何实现它,但也许这是一个好的开始:

using System.Windows.Forms;

public class AutoCompleteTextBox : TextBox {

    private string[] database;//put here the strings of the candidates of autocomplete
    private bool changingText = false;

    protected override void OnTextChanged (EventArgs e) {
        if(!changingText && database != null) {
            //searching the first candidate
            string typed = this.Text.Substring(0,this.SelectionStart);
            string candidate = null;
            for(int i = 0; i < database.Length; i++)
                if(database[i].Substring(0,this.SelectionStart) == typed) {
                    candidate = database[i].Substring(this.SelectionStart,database[i].Length);
                    break;
                }
            if(candidate != null) {
                changingText = true;
                this.Text = typed+candidate;
                this.SelectionStart = typed.Length;
                this.SelectionLength = candidate.Length;
            }
        }
        else if(changingText)
            changingText = false;
        base.OnTextChanged(e);
    }

}

我不确定这是否工作得很好,但我认为这段代码的基础已经足够好了。

【讨论】:

  • 没有意识到这个有内置属性。我不太使用 System.Windows.Forms,我使用它的最后一个版本是 .Net Framework 1.1
【解决方案4】:

这可能不是最好的做事方式,但应该可以:

 this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
 this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

private void textBox1_TextChanged(object sender, EventArgs e)
{
    TextBox t = sender as TextBox;
    if (t != null)
    {
        //say you want to do a search when user types 3 or more chars
        if (t.Text.Length >= 3)
        {
            //SuggestStrings will have the logic to return array of strings either from cache/db
            string[] arr = SuggestStrings(t.Text);

            AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
            collection.AddRange(arr);

            this.textBox1.AutoCompleteCustomSource = collection;
        }
    }
}

【讨论】:

  • SuggestString 不允许运行程序并说“当前上下文中不存在名称 'SuggestStrings'”
  • @mohammad-reza 正如代码中的注释所说 //SuggestStrings 将具有从缓存/数据库返回字符串数组的逻辑。您将必须实施 SuggestStrings。不要指望你只是从 SO 复制代码,它就会开始工作。我们只能为您提供指点。
  • 如何在这个方法中设置Value & Text?例如:Text =“John Peter”,ID =“023”如果我选择“John Peter”如何在代码隐藏中获得“023”?
  • @P.K 你的回答是错误的:System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
  • @dafie 我也收到了这个。似乎 AutoCompleteStringCollection 没有孩子。此外,我发现文本框在此实现中表现得很奇怪,因为我无法使用退格和其他一些问题。如果您只是设置 AutoCompleteCustomSource 一旦它工作没有问题
【解决方案5】:
private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            AutoCompleteStringCollection col = new AutoCompleteStringCollection();
            con.Open();
            sql = "select *from Table_Name;
            cmd = new SqlCommand(sql, con);
            SqlDataReader sdr = null;
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                col.Add(sdr["Column_Name"].ToString());
            }
            sdr.Close(); 

            textBox1.AutoCompleteCustomSource = col;
            con.Close();
        }
        catch
        {
        }
    }

【讨论】:

    【解决方案6】:
    To AutoComplete TextBox Control in C#.net windows application using 
    wamp mysql database...
    
    here is my code..
    
    AutoComplete();
    
    write this **AutoComplete();** text in form-load event..
    
    private void Autocomplete()
        {
            try
            {
                MySqlConnection cn = new MySqlConnection("server=localhost;
    database=databasename;user id=root;password=;charset=utf8;");
                cn.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT distinct Column_Name
         FROM table_Name", cn);
                DataSet ds = new DataSet();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                da.Fill(ds, "table_Name");
                AutoCompleteStringCollection col = new   
                AutoCompleteStringCollection();
                int i = 0;
                for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    col.Add(ds.Tables[0].Rows[i]["Column_Name"].ToString());
    
                }
                textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
                textBox1.AutoCompleteCustomSource = col;
                textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
                cn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
           MessageBoxIcon.Error);
            }
        }
    

    【讨论】:

      【解决方案7】:
          You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
          The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.
      
          USE [DRDOULATINSTITUTE]
          GO
          /****** Object:  StoredProcedure [dbo].[ReikiInsertRow]    Script Date: 5/18/2016 11:12:33 AM ******/
          SET ANSI_NULLS ON
          GO
          SET QUOTED_IDENTIFIER ON
          GO
          ALTER procedure [dbo].[ReikiInsertRow]
          @Reiki varchar(100),
          @emailadd varchar(50)
          as
          insert into dbo.ReikiPowerDisplay
          select Reiki,ReikiDescription, @emailadd from ReikiPower
          where Reiki=@Reiki;
      
      Posted By: Aneel Goplani. CIS. 2002. USA
      

      【讨论】:

        【解决方案8】:

        有两种方法可以实现这个文本框效果:

        使用图形用户界面 (GUI);或使用代码

        使用图形用户界面:
        转到:“属性”标签;然后设置以下属性:

        但是;最好的方法是通过代码创建它。 请参阅下面的示例。

        AutoCompleteStringCollection sourceName = new AutoCompleteStringCollection();
        
        foreach (string name in listNames)
        {    
            sourceName.Add(name);
        }
        
        txtName.AutoCompleteCustomSource = sourceName;
        txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
        txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
        

        【讨论】:

          【解决方案9】:
              private void TurnOnAutocomplete()
              {
                  textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                  textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
                  AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
                  string[] arrayOfWowrds = new string[];
          
                  try
                  {
                      //Read in data Autocomplete list to a string[]
                      string[] arrayOfWowrds = new string[];
                  }
                  catch (Exception err)
                  {
                      MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
                  }
          
                  collection.AddRange(arrayOFWords);
                  textBox.AutoCompleteCustomSource = collection;
              }
          

          您只需在获得自动完成列表所需的数据后调用一次。一旦绑定它就留在文本框。您不需要或不想在每次更改文本框中的文本时调用它,这会杀死您的程序。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-02-01
            • 1970-01-01
            • 2011-04-18
            • 2010-09-22
            • 1970-01-01
            • 2012-10-18
            相关资源
            最近更新 更多