【问题标题】:Text box AutoCompleteSource (winForms) and LINQ query文本框 AutoCompleteSource (winForms) 和 LINQ 查询
【发布时间】:2014-08-24 20:57:55
【问题描述】:

我有一个带有 AutoCompleteCustomSource 的预填充文本框:

var source = new AutoCompleteStringCollection();
using(propertiesManagementDataContext db = new propertiesManagementDataContext())
{
    var q =
        (from t in db.GetTable<Tenant>()
        select t.lname + " " + t.fname).ToArray();
        source.AddRange(q);
}
txt_callerName.AutoCompleteCustomSource = source;
txt_callerName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt_callerName.AutoCompleteSource = AutoCompleteSource.CustomSource;

它工作正常,但我想知道自动完成项目的 ID。如何得到它? 我试过这样,但有一个错误:

var q =
    (from t in db.GetTable<Tenant>()
    select new {lfname = t.lname + " " + t.fname, t.tenantID}).ToArray();
source.AddRange(q); 
//this does not work, because q is not an array of strings anymore

如何自动完成文本框并保存自动完成项的Lname、Fname和tenantID之间的连接?

【问题讨论】:

    标签: c# winforms linq autocomplete


    【解决方案1】:

    我在AutoCompleteStringCollection 类中看不到任何允许您为每个字符串存储额外数据的东西......它几乎只是字符串的集合。

    这并不理想,但您可以在字符串末尾包含 ID,这样它就不会影响用户键入时的自动完成体验,然后在他们做出选择时将值解析回:

    var q =
        (from t in db.GetTable<Tenant>()
         select string.Format("{0} {1} ({2})", t.lname, t.fname, t.tenantID)).ToArray();
    

    或者,您可以使用ComboBox 控件,该控件(如果配置正确)执行您的TextBox 正在执行的所有操作,并且支持将数据源设置为您想要的任何类的集合(不限于字符串集合)。

    然后您将使用DisplayMember 指定对用户可见的属性(名称),然后使用ValueMember 指定每个项目的值(ID)。

    【讨论】:

      【解决方案2】:

      您可以将所有附加数据存储在并行字典(或其他类似集合)中

      var q =
          (from t in db.GetTable<Tenant>()
          select new {lfname = t.lname + " " + t.fname, t.tenantID});
      
      Dictionary<String, Int32> idDictionary = new Dictionary<String, Int32>();
      
      foreach(var item in q)
      {
          idDictionary.Add(item.lfname, item.tenantID);
          source.AddRange(q);
      }
      
      ...
      String currentSuggestion = ...
      
      Int32 id = idDictionary[currentSuggestion];
      dbContext.Entities.RemoveById(id);
      

      这不是理想的解决方案,因为您必须以某种方式将每个 textBox 与 AutoCompletion 关联到它自己的字典(并行存储它,或者子类化 TextBox)。 lfname 也有可能在查询中出现两次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2010-11-20
        • 2017-03-22
        • 2011-02-08
        相关资源
        最近更新 更多