【问题标题】:Searching for record in c# Winform (Entity Framework)在 c# Winform(实体框架)中搜索记录
【发布时间】:2016-02-14 20:06:44
【问题描述】:

我有一个带有文本框的 c# winform,通过实体框架连接到一个名为 Candidates 的表(它有 700 条记录)。 我正在使用一个名为 candidatesBindingSource 的 BindingSource。一切都按我的意愿工作。

只有一件事。我正在尝试使用姓氏搜索候选人。所以我有一个名为 textSurname 的文本框和一个带有此代码的按钮 用于搜索我的记录:

var searchResults = (from a in _context.Candidates where (a.Surname.Contains(textSurname.Text)) select a.Id).ToList();
if (searchResults.Count > 0)
{
    // Id of a record in searchResults is correct
    var position = searchResults[0];
    // This line moves focus to a wrong record
    candidatesBindingSource.Position = position; // 
}

如果找到一条记录,我可以得到它的 ID。在这里我有一个问题。如何将我的 candidatesBindingSource 重新定位到 使用我的搜索结果中的 ID 记录?例如,如果我有一个 Id = 2638,上面的代码重新定位我的candidatesBindingSource 到最后一条记录。我怀疑这部分 candidatesBindingSource.Position 实际上作为记录计数(我的表中为 700) 并且无法前往记录号。 2638(不使用此 ID 的记录)。我对吗?那么如何使用找到的 Id 实现 GOTO 记录? 我真的必须使用带有MoveNext 命令的For 循环来比较我搜索到的ID 和所有ID 吗?

任何提示将不胜感激。

【问题讨论】:

  • 你在candidatesBindingSource.DataSource 里放了什么?
  • 这一行是我的Bindingsource:candidatesBindingSource.DataSource = _context.Candidates.ToList();

标签: c# winforms entity-framework search full-text-search


【解决方案1】:

好的,这就是你初始化绑定源的方式

candidatesBindingSource.DataSource = _context.Candidates.ToList();

那么你就不需要搜索数据库了,你可以像这样使用List.FindIndex method搜索数据源列表:

var candidateList = (List<Candidate>)candidatesBindingSource.DataSource;
var searchText = textSurname.Text;
var firstMatchIndex = candidateList.FindIndex(c => c.Surname.Contains(searchText));
if (firstMatchIndex >= 0)
     candidatesBindingSource.Position = firstMatchIndex;

【讨论】:

  • Ivan Stoev,你教会了我一些全新的东西!它工作得很好而且很快。谢谢你,周末愉快:)
  • @Vladimir 你欢迎朋友。周末愉快,编码愉快!
  • @Vladimir 你可以投票选出好的答案,包括被接受的答案:)
【解决方案2】:

我认为您应该设置为项目的 CandidateBindingSource.Position 索引而不是 id。 该帖子将帮助您正确获取项目索引,而无需再次读取整个数据。 Get Row Index in a list by using entity framework

您也可以尝试从绑定源获取索引。

【讨论】:

    【解决方案3】:

    如果您在上下文之外创建一个列表,它将具有与您在表单上设置的数据绑定相同的索引。要将表单设置为查看搜索结果,您可以使用列表的 FindIndex() 方法中的匹配项,然后将 .Position 设置为该索引。

    using (Candidates _context = new Candidates())
    {    
        var candidateList = _context.Candidate.ToList();
        var firstCandidateMatchIndex = candidateList.FindIndex(c => 
            c.Surname.Contains(textSurname.Text));
        if (firstCandidateMatchIndex >= 0)
            candidateBindingSource.Position = firstCandidateMatchIndex;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多